【问题标题】:Populate View selected record ViewModel填充查看所选记录 ViewModel
【发布时间】:2015-07-21 18:44:15
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

  • 我会采用与信用卡字段相同的方法,并在同一级别添加姓氏、名字等。另一种选择是 Wholesale ViewModel。 IAC,您可以使用 automapper 来减轻痛苦。 lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models
  • 史蒂夫,我正沿着自动映射器路线走,但时间用完了。如果您发布一些代码作为答案,我将非常感激,当然标记为答案。

标签: c# asp.net-mvc viewmodel


【解决方案1】:

根据项目,您可以使用模型-视图-视图模型模式 (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

就个人而言,我发现带有自动映射器的 ViewModel 模式非常适用于数据类型项目的表单。

【讨论】:

    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 2020-07-25
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多