2012-03-16 93 views
0

我有一個簡單的html表單和一個基於默認綁定器的表單對應的模型。 HTTPPOST工作正常,並在提交表單時將所有表單值提供給模型。 但我希望HTTP GET顯示用戶名默認爲Hello的表單。但該視圖顯示一個空白表單。有人可以向我解釋爲什麼默認模型聯編程序無法將值推送到GET請求上的表單,但能夠從POST表單中將值從我的表單中獲取到POST請求中的模型中。謝謝。MVC3模型綁定和GET請求

----- -----控制器

[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> 

回答

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幫助程序將使用模型值生成相應的輸入字段並填充它們。

+0

我想如果默認粘合劑編程,讓他們出來的即使不使用html助手,也可以在帖子上請求並綁定到模型,但它也可以在另一方面工作,而不必使用htmlhelpers。我希望儘可能保持純html視圖。 – 2012-03-16 15:21:46

+0

@RekhaJayaram,模型聯編程序用於解析發佈的值。如果你想在HTML中輸入一個值,你必須使用value屬性: '這正是幫助者所做的。 – 2012-03-16 16:46:10

+0

非常感謝您花時間解釋這一點。這真的幫助我理解發生了什麼。 – 2012-03-16 17:33:00

1

與此更換你的HTML文本框:

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

否則.NET無法填充字段的值...

+0

謝謝你的工作。 – 2012-03-16 15:42:46