Reputation: 131
I have a simple html form, and a model corresponding to the form based on the default binder. The HTTPPOST works fine and gets me all the form values into the model on a submit of the form. However I expected the HTTP GET to display the form with the Username defaulted to Hello. But the view displays a blank form. Could someone kindly explain to me why the default model binder is not able to push the values out to the form on a GET request, but is able to get the values from my form into the model on a POST request. Thanks.
-----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);
}
---MODEL ---
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>
Upvotes: 0
Views: 846
Reputation: 6771
Replace your HTML Textbox with this:
@Html.TextBoxFor(m=>m.UserName)
Otherwise .net is unable to fill the value of the field...
Upvotes: 1
Reputation: 1038730
You need to use HTML helpers to generate your input fields instead of hardcoding them as you did:
@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>
}
The HTML helpers will use the model values to generate the corresponding input fields and populate them.
Upvotes: 1