Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 提交表单时持久化模型属性_C#_Asp.net Mvc - Fatal编程技术网

C# 提交表单时持久化模型属性

C# 提交表单时持久化模型属性,c#,asp.net-mvc,C#,Asp.net Mvc,我试图弄清楚,当我返回带有模型的视图时,为什么属性值没有持久化 Index.cshtml 视图: 控制器: [HttpPost] public ActionResult Index([Bind(Exclude = "Id,ShippingCost")] TestModels model) { //assume the initial value is false. I only want it to switch to true once if (!model.IsWtv)

我试图弄清楚,当我返回带有模型的视图时,为什么属性值没有持久化

Index.cshtml

视图:

控制器:

[HttpPost]
public ActionResult Index([Bind(Exclude = "Id,ShippingCost")] TestModels model)
{
   //assume the initial value is false. I only want it to switch to true once
   if (!model.IsWtv)
      model.IsWtv = true;

   return View(model);
}
型号:

public Boolean IsWtv
{
   get;
   set;
}

重新提交表单时,IsWtv的值始终为false。我不明白为什么?

首先,在处理控制器操作方法时,您应该真正遵循PRG模式(POST、重定向、GET)(除非这是某种类型的AJAX请求)

也就是说,
HtmlHelpers
在更新和返回模型时从模型状态而不是模型中获取模型值。为了更新和返回模型,请在修改任何属性之前在post方法中添加这行代码:

ModelState.Clear();
或者您可以在ModelState本身中设置IsWtv的值:

//no point in doing any check on the actual variable
//we are always returning true
ModelState["IsWtv"].Value = true;

嘿,这成功了!正如你所看到的,我对MVC比较陌生,所以这很有帮助。非常感谢你。@NerdinTraining-任何时候的人-祝你学习顺利!
//no point in doing any check on the actual variable
//we are always returning true
ModelState["IsWtv"].Value = true;