2011-03-09 51 views

回答

18

在ASP.NET MVC中,你不使用<asp:...标签,但你可以尝试张贴任何数量的将表单输入到控制器操作中,其中CustomViewModel类可以绑定到数据并让您进一步操作它。

public class CustomViewModel 
{ 
    public string textbox1 { get; set; } 
    public int textbox2 { get; set; } 
    public string hidden1 { get; set; } 
} 

例如,如果你在MVC 3使用剃刀语法,你的视图可能看起来像:

@using (Html.BeginForm()) 
{ 
    Name: 
    <input type="text" name="textbox1" /> 
    Age: 
    <input type="text" name="textbox2" /> 
    <input type="hidden" name="hidden1" value="hidden text" /> 
    <input type="submit" value="Submit" /> 
} 

然后在你的控制器动作,其自动将这些数据绑定到你的ViewModel类,让我们说它被称为保存,可能看起来像:

[HttpPost] 
public ActionResult Save(CustomViewModel vm) 
{ 
    string name = vm.textbox1; 
    int age = vm.textbox2; 
    string hiddenText = vm.hidden1; 
    // do something useful with this data 
    return View("ModelSaved"); 
} 
+2

应该鼓励使用视图模型,而不是我所了解的FormCollection。 – 2011-03-09 23:10:36

+0

@havok:修改答案以加强视图模型 – 2011-03-10 15:03:45

+0

现在这是一个很好的答案+1 – 2011-03-10 20:30:57

4

在ASP.NET MVC服务器端控件(如asp:Label)不应该被使用,因为它们依赖ViewState和PostBack,它们是ASP.NET MVC中不再存在的概念。所以你可以使用HTML助手来生成输入字段。例如:

<% using (Html.BeginForm()) { %> 
    <%= Html.LabelFor(x => x.Foo) 
    <%= Html.HiddenFor(x => x.Foo) 
    <input type="submit" value="OK" /> 
<% } %> 

,并具有将接收后的控制器操作:

[HttpPost] 
public ActionResult Index(SomeViewModel model) 
{ 
    // model.Foo will contain the hidden field value here 
    ... 
} 
相关问题