2013-11-02 15 views
2

對於MVC4,通過POST發送ViewModel用於將視圖填充回控制器的最佳實踐方式是什麼?通過POST將ViewModel發送回控制器

+0

根據我的理解,您應該'Html.BeginForm' – Satpal

+0

http://stackoverflow.com/questions/5849398/mvc-3-form-post-and-persisting-model-data –

+0

http:// www。 asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-helpers,-forms-and-validation#Exercise3 – CodeCaster

回答

2

讓我們假設你想要一個登錄表單,這個視圖模型:

public class LoginModel 
{ 
    [Required] 
    public string UserName { get; set; } 

    [Required] 
    [DataType(DataType.Password)] 
    public string Password { get; set; } 

    public bool RememberMe { get; set; } 
} 

使用在視圖中這個視圖模型是直接的,只要發送LoginModel的新實例:

public ActionResult Login() 
{ 
    var model = new LoginModel(); 
    return View(model); 
} 

現在,我們可以創建Login.cshtml觀點:

@model App.Models.LoginModel 

@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(model => model.UserName) 
    @Html.TextBoxFor(model => model.UserName) 
    @Html.ValidationMessageFor(model => model.UserName) 

    @Html.LabelFor(model => model.Password) 
    @Html.PasswordFor(model => model.Password) 
    @Html.ValidationMessageFor(model => model.Password) 

    @Html.CheckboxFor(model => model.RemberMe) 
    @Html.LabelFor(model => model.RememberMe) 

    <input type="submit" value="Login" /> 
} 

現在我們要創造一種處理這種形式的後控制器的動作。我們是這樣做的:

[HttpPost] 
public ActionResult Login(LoginModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Authenticate the user with information in LoginModel. 
    } 

    // Something went wrong, redisplay view with the model. 
    return View(model); 
} 

HttpPost屬性將確保控制器動作只能通過POST請求到達。

MVC將使用它的魔力並將視圖中的所有屬性綁定到填充了帖子值的LoginModel實例。

+0

我希望你比RemberMe有更多的錯誤,所以編輯會飛翔〜 – panhandel

1

一種方法是讓您的Post controller接受ViewModel作爲其參數,然後將其屬性映射到您的域模型。

public class Model 
{ 
    public DateTime Birthday {get;set;} 
} 

public class ViewModel 
{ 
    public string Month {get;set;} 
    public string Day {get;set;} 
    public string Year {get;set;} 
} 

控制器

[HttpPost] 
public ActionResult Create(ViewModel viewModel) 
{ 
    string birthday = viewModel.Month + "/" + viewModel.day + "/" + viewModel.year; 

    Model model = new Model { Birthday = Convert.ToDateTime(birthday) } ; 
    // save 
    return RedirectToAction("Index"); 
} 
+0

嗯,我問從_View_怎麼能輕鬆地回發一個模型? –