试图将模型数据从视图传递到控制器

本文关键字:控制器 视图 模型 数据 | 更新日期: 2023-09-27 18:04:34

在我的。net mvc项目中,我试图将我的模型传递给最初传递到视图的控制器。每次都为空

视图代码:

@model Shop.Models.ShoppingModel
...
@using (Html.BeginForm())
         {
             @Html.HiddenFor(model => model.payment.cardNumber)
             @Html.HiddenFor(model => model.payment.cvv)
             @Html.HiddenFor(model => model.payment.expMonth)
             @Html.HiddenFor(model => model.payment.expYear)
             <div class="buttons">
                <a href="@Url.Action("Index", "Cart")"><input type="button" class="button" id="back" value="Continue Shopping"></a>
                <input type="submit" value="Submit Order" class="button" />
             </div>
         }

和控制器代码:

[HttpPost]
    public ActionResult Finish(ShoppingModel sm)
    {
        string[] response = commitTransaction(sm.payment, false);
        if (response[0] == "1") // transaction was approved!
        {
            //TempData["Message1"] = "Your order was placed for a total of " + sm.cartSummary.TotalCost.ToString("c") + " on your " + sm.payment.ccType.ToString() + ".";
            TempData["Message2"] = "You will be receiving an email shortly with your receipt.";
            //ViewBag.Message = new string[] { TempData["Message1"].ToString(), TempData["Message2"].ToString() };
        }
        else
        {
            TempData["Message1"] = "There was an error processing your order.  Our IT dept has been notified about this.";
            //ViewBag.Message = new string[] { TempData["Message1"].ToString() };
        }
        return RedirectToAction("Complete", "Cart");
    }

ShoppingModel:

public class ShoppingModel
{
    [Required]
    public CartSummaryModel.DeliveryModel delivery = new CartSummaryModel.DeliveryModel();
    [Required]
    public CartSummaryModel.PaymentModel payment = new CartSummaryModel.PaymentModel();
    [Required]
    public CartSummaryModel cartSummary = new CartSummaryModel();
    [Required]
    public StudentModel student = new StudentModel();
    [Required]
    public RootObject midas = new RootObject();
}

由于某种原因,Finish方法中ShoppingModel中的变量PaymentModel每次都为空。有人能看出我做错了什么吗?

试图将模型数据从视图传递到控制器

把你的模型改成这样:

public class ShoppingModel
{
    [Required]
    public CartSummaryModel.DeliveryModel delivery { get; set; };
    [Required]
    public CartSummaryModel.PaymentModel payment { get; set; };
    [Required]
    public CartSummaryModel cartSummary { get; set; };
    [Required]
    public StudentModel student { get; set; };
    [Required]
    public RootObject midas { get; set; };
}