簡體   English   中英

使用POST將ViewModel發送回控制器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM