最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - call an c# mvc controller method from jquery using $.getJson Method - Stack Overflow

programmeradmin1浏览0评论

I'm clearly missing something but can't for the life of me see what it is so would appreciate if anyone could point out my error.

I have a simple details page with a form to add ments to the selected detail.

I have a view with the following formed contained within it:

@using (Html.BeginForm("Details", "Home", FormMethod.Post, new { id ="mentForm" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.NewComment.Name);
        @Html.TextBoxFor(model => model.NewComment.Name, new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.NewComment.Body);
        @Html.TextAreaFor(model => model.NewComment.Body, new { @class = "form-control" })
    </div>

    <input type="submit" class="btn btn-primary" value="Add Comment" />
} 

This view then calls the following c# controller method:

        [HttpPost]
        public ActionResult Details(int id,DetailsViewModel model)
        {

            if (!ModelState.IsValid)
                return View(model);

            var content =_data.First(c => c.Id == id);

            content.Comments.Add(model.NewComment);

            return View(new DetailsViewModel(content));
        }

If I use the form without adding any additional code to catch the submit with jquery then this all works correctly.

When i add the following JQuery code to the page then the above server code is not executed (I know i am not actually returning any json in the above method but if the method is not executed that seems redundant for now?):

    $(document).ready(function () {

        $("#mentForm").submit(function (event) {
            event.preventDefault();

            var url = $(this).attr('action');

            $.getJSON(url, $(this).serialize(), function (ment) {
                alert(ment)
            });
        });
    });

If is also worth noting that if i add any alerts around the getjson call then these all fire correctly.

Does anyone have any ideas about what i'm doing wrong?

I'm clearly missing something but can't for the life of me see what it is so would appreciate if anyone could point out my error.

I have a simple details page with a form to add ments to the selected detail.

I have a view with the following formed contained within it:

@using (Html.BeginForm("Details", "Home", FormMethod.Post, new { id ="mentForm" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.NewComment.Name);
        @Html.TextBoxFor(model => model.NewComment.Name, new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.NewComment.Body);
        @Html.TextAreaFor(model => model.NewComment.Body, new { @class = "form-control" })
    </div>

    <input type="submit" class="btn btn-primary" value="Add Comment" />
} 

This view then calls the following c# controller method:

        [HttpPost]
        public ActionResult Details(int id,DetailsViewModel model)
        {

            if (!ModelState.IsValid)
                return View(model);

            var content =_data.First(c => c.Id == id);

            content.Comments.Add(model.NewComment);

            return View(new DetailsViewModel(content));
        }

If I use the form without adding any additional code to catch the submit with jquery then this all works correctly.

When i add the following JQuery code to the page then the above server code is not executed (I know i am not actually returning any json in the above method but if the method is not executed that seems redundant for now?):

    $(document).ready(function () {

        $("#mentForm").submit(function (event) {
            event.preventDefault();

            var url = $(this).attr('action');

            $.getJSON(url, $(this).serialize(), function (ment) {
                alert(ment)
            });
        });
    });

If is also worth noting that if i add any alerts around the getjson call then these all fire correctly.

Does anyone have any ideas about what i'm doing wrong?

Share Improve this question edited Mar 18, 2014 at 10:06 Golda 3,89110 gold badges38 silver badges67 bronze badges asked Dec 17, 2013 at 18:10 user3112308user3112308 231 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

When you are using .getJSON it makes a GET request, and your Details method only answers POST requests.

Try this instead:

$.ajax({
  type: "POST",
  url: url,
  data: $(this).serialize(),
  success: function(ment) {
    alert(ment);
  }
});

Try posting to the controller.

$.getJSON is performing a http get under the covers. Your controller endpoint is expecting a post and will not accept a http get.

Here is a function(blog reference) that will provide the same functionality:

(function ($) {

    $.postJSON = function (url, data) {

        var o = {
            url: url,
            type: "POST",
            dataType: "json",
            contentType: 'application/json; charset=utf-8'
        };

        if (data !== undefined) {
            o.data = JSON.stringify(data);
        }

        return $.ajax(o);
    };

} (jQuery));

Simply add this somewhere after your jQuery include.

use $.post() instead, when you use FormMethod.Post : http://api.jquery./jQuery.post/

发布评论

评论列表(0)

  1. 暂无评论