我有一个带控制器和视图的模型。在“创建”视图中,我添加了一个不属于模型的字段。
如何读取控制器中的字段?
非常感谢。
答案 0 :(得分:2)
您可以访问Request.Form["Property"]
来访问视图模型中不存在的属性。请参阅以下示例:
https://dotnetfiddle.net/riyOjb
但是,建议您查看模型。
public class SampleViewModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new SampleViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(SampleViewModel model)
{
// model.Property1 is accessable here
// as well as model.Property2
// but if you want something not in the view model, use Request.Form
ViewData["CustomProperty"] = Request.Form["CustomProperty"];
return View(model);
}
}
@model MvcApp.SampleViewModel
@using(Html.BeginForm())
{
@Html.TextBoxFor(m => m.Property1)<br /><br />
@Html.TextBoxFor(m => m.Property2)<br /><br />
<input type="text" name="CustomProperty" id="CustomProperty" /><br /><br />
<button type="submit" class="btn">Submit</button>
}
<h2>Submitted Data</h2>
@Model.Property1<br />
@Model.Property2<br />
@ViewData["CustomProperty"]