我在ASP.NET MVC中遇到了问题,需要从视图传递数据到控制器。我的模型如下:
public class InputModel {
public List<Process> axProc { get; set; }
public string ToJson() {
return new JavaScriptSerializer().Serialize(this);
}
}
public class Process {
public string name { get; set; }
public string value { get; set; }
}
我在控制器中创建了这个InputModel,并将其传递给视图:
public ActionResult Input() {
if (Session["InputModel"] == null)
Session["InputModel"] = loadInputModel();
return View(Session["InputModel"]);
}
在我的Input.cshtml文件中,我有一些代码来生成输入表单:
@model PROJ.Models.InputModel
@using(Html.BeginForm()) {
foreach(PROJ.Models.Process p in Model.axProc){
<input type="text" />
@* @Html.TextBoxFor(?? => p.value) *@
}
<input type="submit" value="SEND" />
}
当我点击提交按钮时,我希望使用输入文本框中的数据。 问题1:我看到过@Html.TextBoxFor(),但是我不太明白这个“stuff => otherstuff”。我得出结论,"otherstuff"应该是我想要将数据写入的字段,在这种情况下可能是“p.value”。但箭头前面的“stuff”是什么?
在控制器中,我有一个用于POST的函数,并进行了一些调试:
[HttpPost]
public ActionResult Input(InputModel m) {
DEBUG(m.ToJson());
DEBUG("COUNT: " + m.axProc.Count);
return View(m);
}
这里的调试信息只显示类似于:
{"axProc":[]}
COUNT: 0
所以我得到的Model是空的。
问题2:@using(Html.BeginForm())这个用法有基本错误吗?如果不是正确的选择,那么我如何将填充了数据的Model返回给控制器?(因为上面的示例已经缩写,实际代码中会有更多内容,所以我不能在此处使用"@model List< Process >"。)
希望有人能补充一些我忽略的细节。