开发者

MVC 3 $.post works but $.ajax doesn't

I have a simple model

namespace 开发者_Python百科StackOverflow.Models
{
    public class Test
    {
        public Test()
        {
            Name = "Test";
            Subs = new List<Sub>();
            Subs.Add(new Sub { Num = 1, SubName = "A" });
            Subs.Add(new Sub { Num = 2, SubName = "B" });
        }

        public string Name { get; set; }
        public List<Sub> Subs { get; set; }
    }

    public class Sub
    {
        public int Num { get; set; }
        public string SubName { get; set; }
    }
}

and associated view

@model StackOverflow.Models.Test

<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/JScript1.js")" type="text/javascript"></script>

@{
    ViewBag.Title = "Test";
}

<h2>Test2</h2>

@using (Html.BeginForm())
{

    <p>Test Name</p>   
    @Html.EditorFor(m => m.Name)

    <p>Sub 1</p>
    @Html.EditorFor(m => m.Subs[0].Num)
    @Html.EditorFor(m => m.Subs[0].SubName)

    <p>Sub2</p>
    @Html.EditorFor(m => m.Subs[1].Num)
    @Html.EditorFor(m => m.Subs[1].SubName)

    <div id="result"></div>

    <br />

    <input type="submit" value="create" />
}

With the controller actions being

    public ActionResult Test()
    {
        Test test = new Test();

        return View(test);
    }

    [HttpPost]
    public PartialViewResult Test(Test test)
    {
        if (ModelState.IsValid)
        {
            return PartialView("_Results", new Result {Value = "Pass"});
        }
        else
        {
            return PartialView("_Results", new Result { Value = "Fail" });
        }
    }

The PartialView is simply showing the text string.

I am using the following javascript to do the post

$('form').submit(function (e) {
    $(':submit', this).attr('disabled', true);
    e.preventDefault();


    $.post($(this).attr("action"), $(this).serialize(), function (data) {
        $("#result").html(data);
        alert("hurray");

    });
    return false;
});

Everything works fine (and in the real code I have a jQueryUI modal dialog appear on the submit click and closed when the post returns)

I figured that I need to use $.ajax so I can have an "error:" function to remove the jQueryUI modal dialog should anything go wrong. This is where I have run into problems and for the life of me I cant work out what I am doing wrong

This was my first attempt and I simply get the alert("error") appear on post.

   $.ajax({
        url: $(this).attr("action"),
        type: "POST",
        data: $(this).serialize(),
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            alert("success!");
        },
        error: function () {
            alert("error!!");
        }
    });

I have also tried passing the following to "data:"

JSON.stringify($("form").serializeArray());

When I look at the "test" in the controller action I see that it doesn't contain any data

I also tried simply passing in

($("form").serializeArray()

and just get the "error" alert.

Can anyone please help me resolve this?

Many thanks.


The problem is in this line:

contentType: "application/json; charset=utf-8",

This sets the content-type header for the request. It does not specify anything for the response. You are creating your data string with serialize: this means that it will be in normal a=value&b=othervalue format, which is emphatically not JSON.

Remove the contentType line. jQuery will set the correct request header (application/x-www-form-urlencoded for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜