MVC3模型绑定和GET请求

时间:2012-03-16 14:08:17

标签: asp.net-mvc-3

我有一个简单的html表单,以及一个基于默认绑定器的表单对应的模型。 HTTPPOST工作正常,并在表单提交时将所有表单值转换为模型。 但是我希望HTTP GET能够显示用户名默认为Hello的表单。但视图显示一个空白表单。有人可以向我解释为什么默认模型绑定器无法将值推送到GET请求中的表单,但是能够在POST请求中将我的表单中的值提取到模型中。感谢。

----- CONTROLLER -----

[HttpPost]
    public ActionResult Index(SimpleFormModel application)
    {
        return View(application);
    }
[HttpGet]
    public ActionResult Index ()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        SimpleFormModel simplefm = new SimpleFormModel();
        simplefm.UserName = "Hello";
        return View(simplefm);
    }

---模型---

public class SimpleFormModel
{
    public string UserName { get; set; }
    public string Dob { get; set; }
    public string Email { get; set; }

}

-------- VIEW --------------------------

@model MVC3MobileApplication.Models.SimpleFormModel
@{
ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>


<form action="">
<fieldset>
<legend>Personal information:</legend>
Name: <input type="text" size="30" name="SimpleFormModel.UserName" /><br />
E-mail: <input type="text" size="30" name ="SimpleFormModel.Email"/><br />
Date of birth: <input type="text" size="10" name ="SimpleFormModel.Dob"/>
</fieldset>
</form> 

2 个答案:

答案 0 :(得分:1)

您需要使用HTML帮助程序生成输入字段,而不是像以前那样对其进行硬编码:

@model MVC3MobileApplication.Models.SimpleFormModel

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>

@using (Html.BeginForm())
{
    <fieldset>
        <legend>Personal information:</legend>
        Name: @Html.TextBoxFor(x => x.UserName, new { size = "30" })
        <br />
        E-mail: @Html.TextBoxFor(x => x.Email, new { size = "30" })
        <br />
        Date of birth: @Html.TextBoxFor(x => x.Dob, new { size = "10" })
    </fieldset>

    <button type="submit">OK</button>
}

HTML帮助程序将使用模型值生成相应的输入字段并填充它们。

答案 1 :(得分:1)

将HTML文本框替换为:

@Html.TextBoxFor(m=>m.UserName)

否则.net无法填写该字段的值......

相关问题