Ajax将模型发布到控制器动作

时间:2015-05-23 01:04:34

标签: ajax asp.net-mvc

在mvc4中我试图使用 Jquery Ajax 将模型数据从视图发布到控制器,但现在不知道这个代码有什么问题可以帮助我解决这个问题。

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>

<script type="text/javascript">

    $(document).ready(function () {
        $("#save").click(function () {
            $("#content").html("<b>Please Wait...</b>");
            var dataObject = {
                empid: 1,
                EmployeeName: "rizwan",
                Address: "lahore",
                Country: "pakistan",
                Salary: "35000.00",
                DepartmentName: "Field"
            }
            $.ajax({
                type: "POST",
                url: "/Home/Index",
                data: dataObject,
                success: function (data)
                { 
                    $("#empname").val(''),
                    $("#empadd").val(''),
                    $("#empcountry").val(''),
                    $("#empsalary").val(''),
                    $("#empdeptname").val(''),
                    $("#content").html("<div class='success'>"+data+"</div>")
                },
                error: function (ehr)
                {
                    $("#content").html("<div class='failed'>Error! Please try again</div>");
                },
            })
        });
    });
</script>

这是我的控制器动作代码,它只接收对象的值并保存到数据库中 问题是我未能在控制器操作端收到值。
请帮帮我......

[HttpPost]
public ActionResult Index(userview dataObject)
{         
    department dept = new department();
    employee emp = new employee();
    string message = "";
    try
    {
        emp.employeeName = dataObject.EmployeeName;
        emp.address = dataObject.Address;
        emp.country = dataObject.Country;
        emp.salary = dataObject.Salary;
        dept.departmentName = dataObject.DepartmentName;
        db.employees.Add(emp);
        db.departments.Add(dept);
        db.SaveChanges();
    }
    catch(Exception ex)
    {
         message = "Error! Please try again";
    }
    if (Request.IsAjaxRequest())
    {
        return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
    ViewBag.message = message;
    return View();
}

这是我的模特课

   public class userview
    {

        public int empId { get; set; }
        public string EmployeeName { get; set; }
        public string Address { get; set; }
        public string Country { get; set; }
        public decimal Salary { get; set; }
        public string DepartmentName { get; set; }


    }

2 个答案:

答案 0 :(得分:0)

尝试使用 JSON.stringify

$.ajax({
                type: "POST",
                url: "/Home/Index",
                data: JSON.stringify(dataObject), //Here is the change
                success: function (data)
                { 
                    $("#empname").val(''),
                    $("#empadd").val(''),
                    $("#empcountry").val(''),
                    $("#empsalary").val(''),
                    $("#empdeptname").val(''),
                    $("#content").html("<div class='success'>"+data+"</div>")
                },
                error: function (ehr)
                {
                    $("#content").html("<div class='failed'>Error! Please try again</div>");
                },
            })

答案 1 :(得分:0)

您可以自己实现BindModel!获取json字符串并反序列化为您的实体。

public class JsonBinder<T> : System.Web.Mvc.IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        using (var reader = new System.IO.StreamReader(controllerContext.HttpContext.Request.InputStream))
        {
            //set stream position 0, maybe previous action already read the stream.
            controllerContext.HttpContext.Request.InputStream.Position = 0;
            string json = reader.ReadToEnd();
            if (string.IsNullOrEmpty(json) == false)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                object jsonData = serializer.DeserializeObject(json);
                return serializer.Deserialize<T>(json);
            }
            else
            {
                return null;
            }
        }
    }
}

并将JsonBinder设置为post方法,例如

[HttpPost]
public ActionResult Index([ModelBinder(typeof(JsonBinder<userview>))] userview dataObject)
{
}

其他解决方案

我发现您可以将DataContract设置为Model类,并将DataMember设置为该类的Properties。

像这样编辑课程

[DataContract]
public class userview
{
    [DataMember]
    public int empId { get; set; }
    [DataMember]
    public string EmployeeName { get; set; }
    [DataMember]
    public string Address { get; set; }
    [DataMember]
    public string Country { get; set; }
    [DataMember]
    public decimal Salary { get; set; }
    [DataMember]
    public string DepartmentName { get; set; }
}

,您应该添加库引用“ System.Runtime.Serialization”

希望它对您有用。