从视图中检索整个模型

本文关键字:模型 检索 视图 | 更新日期: 2023-09-27 18:09:05

我有一个ASP。. NET MVC项目,在这里我使用一个模型类。我有大约10个变量需要从控制器获取到视图,然后再返回到控制器。目前,我一直将它们存储在模型中,将变量读取为隐藏的输入字段,然后使用NameValueCollection这样:


Html:

<input type="hidden" id="field1" name="field1" value="@Model.variable1" />
<input type="hidden" id="field2" name="field2" value="@Model.variable2" />
<input type="hidden" id="field3" name="field3" value="@Model.variable3" />
<input type="hidden" id="field4" name="field4" value="@Model.variable4" />
<input type="hidden" id="field5" name="field5" value="@Model.variable5" />
<input type="hidden" id="field6" name="field6" value="@Model.variable6" />
c#

System.Collections.Specialized.NameValueCollection nvc = Request.Form;
model.variable1= int.Parse(nvc["field1"]); 
//read the rest of the data into the model

注:values s和name s已被编辑为简单


有更好的方法吗?理想情况下,我想通过我的整个模型返回到我的控制器,但我已经寻找了一个没有成功的解决方案。

从视图中检索整个模型

不需要手动编写html输入或直接从请求中解析数据。表单对象。MVC框架会在内部为你完成所有这些。

public class MyModel 
{
    public string Variable1 {get;set;}
    public string Variable2 {get;set;}
    //....
}

视图:

For结尾的这些方法的特殊之处在于,当您指定模型的属性时,它们将使用构建具有正确id和名称属性的html输入。

@model MyModel
@Html.HiddenFor(x=> x.Variable1)
@Html.HiddenFor(x=> x.Variable2)
//...
控制器动作:

[HttpGet]
public ActionResult SomeAction()
{
     var model = new MyModel();
     model.Variabl1 = "hi";
     return View(model);
}
[HttpPost]
public ActionResult SomeAction(MyModel model)
{
    model.Variable1
}

您也可以发送自定义对象的列表,并在返回时持久化它们,但这有点复杂,并且超出了本答案的范围。