我有一个正在启动的 MVC 3 项目,使用的是 C# 和 Razor。我有一个页面,其中包含大约 20 个将要使用的输入字段。我创建我的 ViewModel 以将数据传递给 View 以创建页面。当用户提交表单时,我对如何获取字段的值感到困惑。
我的 Controller 是否必须为我页面上的每个输入字段设置一个参数?有没有办法让 Controller 获取页面上的所有数据,然后我可以解析它?参数列表会很大。
最佳答案
您可以只使用传递给 View 的同一模型作为后续操作中的参数。
一个例子:
//This is your initial HTTP GET request.
public ActionResult SomeAction() {
MyViewModel model;
model = new MyViewModel();
//Populate the good stuff here.
return View(model);
}
//Here is your HTTP POST request; notice both actions use the same model.
[HttpPost]
public ActionResult SomeAction(MyViewModel model) {
//Do something with the data in the model object.
}
第二种方法中的模型对象将自动从 HTTP 请求中包含的数据填充(技术名称为“模型绑定(bind)”)。
关于c# - 如何检索 MVC 页面上所有输入的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11513426/