使用AJAX将Model从View传递给Controller时模型未定义

时间:2016-06-28 03:14:42

标签: asp.net-mvc asp.net-ajax

当我尝试使用调试器时;在ajax中检查我是否能够序列化表单,它说它是“未定义”。我没有遇到错误但是我在视图中输入的值没有传递给控制器​​。这是我的参考https://stick2basic.wordpress.com/2013/04/14/how-to-pass-model-from-view-to-controller-using-jquery/

查看

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnsubmit').click(function (e) {
            e.preventDefault();
            if ($("#OrderForm").valid()) { //if you use validation
                $.ajax({
                    url: $("#OrderForm").attr('action'),
                    type: $("#OrderForm").attr('method'),
                    data: $("#OrderForm").serialize(),
                    success: function (data) {
                        alert("success");
                    }
                });
            }
        });
    });
</script>

@using (Html.BeginForm("_Order", "Account", FormMethod.Post, new { id =  "OrderForm" }))
{
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
}

控制器

[AllowAnonymous]
        [HttpPost]
        public ActionResult _Order(OrderModel model)
        {
List<OrderModel> orderlist = new List<OrderModel>();
            if (Session["OrderList"] != null)
            {
                orderlist = Session["OrderList"] as List<OrderModel>;
                orderlist.Add(model);
            }
            Session["OrderList"] = orderlist;
            return PartialView();
}

MODEL

public class OrderModel
    {
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        [StringLength(35)]
        public string FirstName { get; set; }
        [StringLength(35)]
        public string MiddleName { get; set; }
        [StringLength(35)]
        public string LastName { get; set; }
        [StringLength(255)]
        public string Address { get; set; }
        [StringLength(40)]
        public string Province { get; set; }
        [StringLength(40)]
        public string Town { get; set; }
        [StringLength(13)]
        public string MobileNo { get; set; }

        [Required(ErrorMessage = "Please fill up Merchant Email.")]
        [DataType(DataType.EmailAddress)]
        public string MerchantEmail { get; set; }

        [Required(ErrorMessage = "Please enter the exact amount.")]
        [DataType(DataType.Currency)]
        public float OrderAmount { get; set; }

        public string OrderSkuCode { get; set; }

        [Required(ErrorMessage = "Please fill up order details.")]
        [StringLength(5000)]
        public string OrderDetails { get; set; }

    }

1 个答案:

答案 0 :(得分:0)

您正在同时做两件事,您可以使用ajax或将数据直接发布到控制器。

@using (Html.BeginForm("_Order", "Account", FormMethod.Post, new { id =  "OrderForm" }))
{
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
}

在这里,您将数据直接发布到控制器(Ajax用于异步传输),这将通过脚本中的Ajax请求传递。

如果你想通过Ajax发布它,那么你需要做的代码更改

<form id="form1">
<div class="form-group">
            <div class="col-md-3">
                @Html.LabelFor(model => model.MerchantEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            </div>
            <div class="col-md-9">
                @Html.TextBoxFor(model => model.MerchantEmail, new { @Value = "abc@gmail.com",@class = "form-control" })
                @Html.ValidationMessageFor(model => model.MerchantEmail, "", new { @class = "text-danger" })
            </div>
        </div>

<div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" id="btnsubmit" class="btn btn-primary" />
            </div>
        </div>
 </form>


<script type="text/javascript">
    $(document).ready(function () {
        $('#btnsubmit').click(function (e) {
            e.preventDefault();
            var data = new FormData($("#form1")[0]);
            if ($("#OrderForm").valid()) { //if you use validation
                $.ajax({
                    url: '@Url.Action("_Order","Your Controller Name")',
                    dataType: "json",
                    data: data,
                    success: function (data) {
                        alert("success");
                    }
                });
            }
        });
    });
</script>