填充视图选定的记录ViewModel

本文关键字:记录 ViewModel 视图 填充 | 更新日期: 2023-09-27 18:03:46

我正在尝试使用ViewModel,因为我喜欢它验证的方式。

我的视图模型:

public class CCvm
{
    [Required(ErrorMessage = "Please enter your Name")]
    public string cardHolderName { get; set; }
    [Required(ErrorMessage = "Please enter your Credit Card Number")]
    public string cardNumber { get; set; }
    [Required(ErrorMessage = "Please enter your Expiration Date MMYY")]
    [StringLength(4, ErrorMessage = "Expiration Date Format MMYY", MinimumLength = 4)]
    public string cardExpirtyDate { get; set; }
    public Wholesale wholesale { get; set; }
}

如何将批发商中选定的人员和卡片信息传递给视图?

我的控制器:

public ActionResult Pay()
{
    if (Session["wID"] == null)
    {
        return RedirectToAction("Index");
    }
    ViewBag.Step = 2;
    if (Session["wID"] == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    //Wholesale wholesale = db.Wholesales.Find(Session["wID"]);
    int wID=Convert.ToInt32(Session["wID"]);
    CCvm ccvm = new CCvm();
    var dude = from d in db.Wholesales
               where d.ID==wID
               select d;
    ccvm.wholesale = (dude.ToList());
    if (ccvm == null)
    {
        return HttpNotFound();
    }
    return View(ccvm);
}

视图有来自批发商表的字段,我想使用VM来验证和控制器来更新。它还具有我需要VM验证并传递给控制器进行处理的卡片信息。

@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName, "", new { htmlAttributes = new { @placeholder = "First Name Please", @class = "text-danger" } })
<input type="text" name="cardExpirtyDate" style="width:40px" />MMYY
<br />@Html.ValidationMessageFor(model => model.cardExpirtyDate)

填充视图选定的记录ViewModel

根据项目的不同,您可以使用Model-View-ViewModel模式(https://msdn.microsoft.com/en-us/library/Ff798384.aspx)。这里有一篇关于使用automapper的好文章:https://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models

如果你想看相反的观点,这里有一篇文章讨论这些观点:http://www.uglybugger.org/software/post/friends_dont_let_friends_use_automapper

就我个人而言,我发现带有automapper的ViewModel模式对于数据类型项目的表单来说工作得非常好。