当HTML页面重新加载时,使用c#来改变它
Change HTML page by using C# when it reloads
在我的html页面中,我在页面顶部设置了一个默认警告,要求填充所有输入区域。
<span style="color:gray" class="help-block">Please enter value for all input fields.</span>
这是一个添加一些东西到数据库的页面。当我点击"添加"按钮时,它在我的C#
代码中重定向ActionResult
。在这里面,根据输入的值,我的代码要么插入的东西到数据库或重新加载添加页面,这意味着不成功的插入。
[HttpPost]
public ActionResult InsertStuff(Stuff stuff)
{
if (stuffManager.InsertStuff(stuff))
return RedirectToAction("ListStuffs", "StuffController"); //successfully inserted!!
else
return RedirectToAction("AddNewStuffForm", "StuffController"); //reload page, here is where i'd like to change warning in html
}
在其他部分,我想加载相同的AddNewStuffForm
页面,但我希望我的警告改变颜色从灰色到红色,如:
<span style="color:red" class="help-block">Please enter value for all input fields.</span>
我不知道如何做到这一点,正如我推断的那样,我需要在else
部分的C#
代码中向html
发送一些东西,但我不知道如何做到这一点。我真的做了一些研究和一些解决方案提供使用一些方法,如Page_Load
。然而,我在html
真的是初学者水平,我在提供解决方案方面有困难。有人能简单地解释一下该怎么做吗?
有很多方法可以做到这一点,你可以在ViewData中为你的其他部分存储检查值,可以在渲染视图中重新检查ViewData值并相应地改变你的样式,就像这样
<span style="color:@(ViewData["fail"])%;" class="help-block">Please enter value for all input fields.</span>
谢谢你
看起来你的思路是对的。
- 通常,在成功的 POST之后,您将重定向到新页面。
- 在不成功的 POST之后,您将保持在同一页面上,并显示相应的错误。这是你目前写错的地方。
因此,在您的实例中,您可以直接返回当前页面,而不是在错误之后进行重定向。没有看到你用来生成初始页面的代码,我不知道在你的情况下会是什么样子,但它通常是这样的:
[HttpPost]
public ActionResult InsertStuff(Stuff stuff)
{
if (stuffManager.InsertStuff(stuff))
return RedirectToAction("ListStuffs", "StuffController"); //successfully inserted!!
else
return View("AddNewStuffForm", "StuffController", stuff); //reload page, here is where i'd like to change warning in html
}
这里的第三个参数是您的原始模型-通常可以使用用户输入的值重新填充页面。
在ASP中,我通常也会首先验证用户输入。你可以使用ModelState.IsValid
将ViewData
填充如下:
[HttpPost]
public ActionResult InsertStuff(Stuff stuff)
{
if (stuffManager.InsertStuff(stuff)){
return RedirectToAction("ListStuffs", "StuffController");//successfully inserted!!
ViewData["PageMessage"] = "The message you want to print in case of success";
}
else{
return RedirectToAction("AddNewStuffForm", "StuffController"); //reload page, here is where i'd like to change warning in html
ViewData["PageMessage"] = "The message you want to print in case of fail";
}
}
然后在视图的ViewData
中打印您的消息,如下所示:
<p style="color:red;">@ViewData["PageMessage"]</p>
相关文章:
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- 为什么使用immutableJS我的状态没有改变
- 是否可以使用“;document.all”;在IE11中,而不改变每次使用
- 如何使用Javascript点击后使形状改变颜色
- 如果我在jquery移动中使用“onclick”,按钮不会改变颜色
- 使用输入类型=“0”改变Circle谷歌地图的半径;“范围”;
- 当道具函数改变状态时,我该如何使用redux
- 使用下拉菜单更改变量值
- Angular.js:为什么使用简单的帮助程序函数改变$scope会导致未插值的 {{..}} 表达式
- 为什么使用 grunt-contrib-cssmin 会改变我的 css,而它应该只缩小它
- 使用离子框架改变全局函数的状态
- Dom 字符串在使用 jQuery attr 操作后不会改变
- 可以't使用“t”改变网页的位置;window.oneforeunload”;
- 使用点击事件来改变“;焦点”;
- 使用 javascript 在 Android 中改变方向
- 改变“;背景图像:“;在计时器上使用javascript无法工作
- 使用YUI来改变输入值
- 改变“;x〃;在背景位置:“;x〃;px”;y”;px为类使用jQuery/Javascript
- jQuery模板不加载时,我使用改变方法
- Knockout JS:使用改变DOM的旧验证代码