[英]Send ViewModel back to controller with POST
對於MVC4,通過POST
發送用於填充視圖的ViewModel
的最佳實踐方法是什么?
假設您要使用此視圖模型登錄表單:
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.RememberMe)
@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
屬性將確保只能通過發布請求來達到控制器操作。
MVC將使用它的魔力並將視圖中的所有屬性綁定回用該帖子中的值填充的LoginModel
實例。
一種方法是讓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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.