这实际上是两个问题合二为一。
第一个问题是关于以下方面的:
<div class="form-group">
@Html.LabelFor(model => model.xxx, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.xxx , new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.xxx, "", new { @class = "text-danger" })
</div>
</div>
我不明白这model => model.xxx
意味着什么,我知道它在做什么,但是我不知道如何解释语法。
第二个问题是,例如,如果我有-
foreach (var item in Model)
我该如何更换
@Html.EditorFor(model => model.xxx , new { htmlAttributes = new { @class = "form-control" } })
和
@Html.EditorFor(item.stringProperty , new { htmlAttributes = new { @class = "form-control" } })
当我尝试此操作时,它给了我错误,是否有一个重载的EditorFor helper接受此信息?
谢谢你!
一个视图可以具有0或1个从控制器发送的模型。
public class Person
{
public string Name {get;set;}
public int Age {get;set;}
}
public ViewResult Index()
{
Person p = new Person() { Name = "P1", Age = 100};
return View(p);//
}
如果您的视图的名称为“索引”,则可以使用第二种方法查看,其中包含2个参数:ViewName
和model
return View("Index", model: p);
那么View
您可以使用model
,如果已实现以下功能:
@model Person//and remember about namespace
@
{
...
}
@using(Html.BeginForm("ActionName", "controllerName", FormMethod.Post))
{
@Html.EditorFor(model => model.Name); // it create input, check in F12 in your browse - then you can exactly understand.
}
如果要为项目创建编辑器,则必须使用:
@Html.TextBox("YourName")
例如:
@using(Html.BeginForm("Action", "controller")
{
@Html.TextBox("YourName")
<input type="submit" value="ok"/>
}
并在您的controller
控制器中:
public ViewResult Action(string YourName)
{
//here you got value for string YourName
return View();
}
并在这里有帮助地回答:ASP.NET MVC获取文本框输入值
编辑,回答有关确切问题的信息(包含在问题下方的评论中):
我有一个列表,我想为列表中的每个项目显示一个输入文本框,但是我希望每个文本框在创建时都在其中包含文本,列表中每个项目的文本(来自该项目的属性)
@foreach(var item in Model)
@using(Html.BeginForm("MyMethod", "Controller"))
{
@Html.TextBox("item", item)
<input type="submit" value="ok" />
}
并在您的控制器中添加MyMethod
:
[HttpPost]
public ViewResult MyMethod(string item)
{
...
}
或者
[HttpPost]
public ViewResult MyMethod(int item) //if it's an int
{
...
}
如果您想拥有更好的安全页面,请阅读以下内容Html.AntiForgeryToken
:http : //msdn.microsoft.com/zh-cn/library/dd470175(v=vs.118).aspx
@using(Html...())
{
@Html.AntiForgeryToken()
(...)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句