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

时间:2014-05-22 16:15:24

标签: c# asp.net-mvc

在我的.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每次都为null。谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:3)

将您的模型更改为:

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; };

}