asp.net查看语法和html助手

时间:2014-10-07 00:43:22

标签: c# asp.net asp.net-mvc html-helper

这实际上是两个问题。

第一个问题是关于以下内容:

<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帮助器接受了这个?

谢谢你!

2 个答案:

答案 0 :(得分:1)

我看到你已经得到了第一个问题的答案。

对于第二个,我认为

@Html.EditorFor(item => item.stringProperty , new { htmlAttributes = new { @class = "form-control" } })

可以正常使用

答案 1 :(得分:1)

一个视图可以有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);//
}

如果您的视图名称&#34;索引&#34;然后你可以使用View的第二种方式,它包含2个参数: ViewNamemodel

return View("Index", model: p);

然后在您的View中,您可以使用model,如果已经实施了这个:{/ p>

@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 get textbox input value

编辑,回答有关确切问题(问题中包含以下评论):

我有一个列表,我想为列表中的每个项目显示一个输入文本框,但是我希望每个文本框在创建时都有文本,来自列表中每个项目的文本(即将出现)来自项目的财产)

@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.AntiForgeryTokenhttp://msdn.microsoft.com/en-us/library/dd470175(v=vs.118).aspx

@using(Html...())
{
@Html.AntiForgeryToken()
(...)
}
相关问题