填充查看所选记录ViewModel

时间:2015-07-21 18:44:15

标签: c# asp.net-mvc viewmodel

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

我的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);
}

View包含来自Wholesaler表的字段,我希望使用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)

1 个答案:

答案 0 :(得分:0)

根据项目的不同,您可以使用Model-View-ViewModel Pattern(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模式对于数据类型项目的表单非常有效。