2015-07-21 68 views
-1

我想使用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); 
} 

查看已經從批發商表中的字段,我想用虛擬機來驗證和控制器進行更新。它也有我需要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

我會採用與信用卡字段相同的方法,並在同一級別添加LastName,FirstName等。另一種選擇是批發視圖模型。 IAC,你可以使用automapper來緩解痛苦。 https://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/ –

+0

史蒂夫,我沿着automapper路線走了,但耗盡了時間。如果你張貼一些代碼作爲答案,我會非常感激它,當然標記爲答案。 –

回答

0

根據項目的不同,您可以使用模型 - 視圖 - 視圖模型模式(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可以非常好地處理數據類型項目上的表單。