tryupdatemodel无法通过ajax调用?

时间:2011-07-22 02:32:49

标签: c# asp.net-mvc-2 jquery

我想通过ajax调用将我的模型发布到服务器。不幸的是,模型没有更新?

 <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<form id="ajaxForm" action="">
    <div>
        name:<%= Html.TextBoxFor(model => model.number) %>
    </div>
    <%--hidden vars--%>
    <input type="hidden" id="Hidden1" />
    <%= Html.Hidden("myModel", Model.Serialize())%>
</form>
<button id="submitbutton">
    save
</button>

<script type="text/javascript">

    $(document).ready(function () {
        $("#submitbutton").click(function () {
            var FormData = $("#ajaxForm").serialize();
            $.ajax({
                type: 'POST',
                url: "/Home/SaveAjax",
                data: { inputdata: $("#myModel").val() },
                datatype: 'JSON'
            });
        })
    });

</script>




    [HttpPost]
    public JsonResult SaveAjax(string inputdata)
    {
        MyModel myModel = (inputdata.DeSerialize() ?? TempData["myModel"] ?? new MyModel()) as MyModel;

        //TryUpdateModel does not update my model??
        TryUpdateModel(myModel);

        TempData["myModel"] = myModel;

        return Json(new { resultaat = "finished" });
    }


 [Serializable]
public class MyModel
{
    //[Required]
    public string name { get; set; }
    public bool flag { get; set; }
    public int number { get; set; }
    public string address { get; set; }
    public string abn { get; set; }
    public string postalcode { get; set; }
}


public static class Extensions
{
    public static string Serialize(this object myobject)
    {
        var sw = new StringWriter();
        var formatter = new LosFormatter();
        formatter.Serialize(sw, myobject);
        return sw.ToString();
    }

    public static object DeSerialize(this string mystring)
    {
        if (string.IsNullOrEmpty(mystring))
            return null;
        var formatter = new LosFormatter();
        MyModel mym = (MyModel)formatter.Deserialize(mystring);
        return mym;
    }
}

1 个答案:

答案 0 :(得分:2)

在您的AJAX请求中,您只发送隐藏字段的值:

data: { inputdata: $("#myModel").val() }

所以你不能期望在服务器上获得任何其他值而不是这个隐藏字段。如果要POST整个表单内容,请使用您在代码中声明但未使用的formData变量:

$('#submitbutton').click(function () {
    var formData = $('#ajaxForm').serialize();
    $.ajax({
        type: 'POST',
        url: '/Home/SaveAjax',
        data: formData,
        dataType: 'json'
    });
});