简体   繁体   中英

How to get the data from json to MVC4 c#?

I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:

JavaScript:

$("#subnt").click(function (event) {
        event.preventDefault();
        var url = "/Home/Submit";
        $.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
            if (data.Success === true) {
                $("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal');   // loads the page into 'min-content' section
            }
            else {
                // display error message
            }
        })
    });
});

C#:

[HttpPost]
public JsonResult Submit()
    {
        return Json(new { Success = true, SomeOtherData = "testing" });
    }

Please check below working code -

I have used exactly your working code -

    [HttpPost]
    public JsonResult Submit()
    {
        return Json(new { Success = true, SomeOtherData = "testing" });
    }

Then I used following JQuery to hit the above action -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $('#click').click(function (e) {
            $.ajax({
                url: "@Url.Action("Submit")",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (response) {
                    alert(response);
                },
                success: function (data) {
                    if (data.Success == true)
                        alert(data.SomeOtherData);
                }
            });
        });
    });
</script>

<input type="submit" value="click" id="click" />

And as the output I was able to get an alert as shown below -

在此处输入图片说明

Easiest thing to do is use the superior json.net

[HttpPost]
public string Submit()
{
    var result = new { success = true, someOtherDate = "testing"};
    var json = JsonConvert.SerializeObject(result);
    return json;
}

Your code is ok bu you can add debugger.and open d eveloper tools check your data .

$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
             debugger;
            if (data.Success === true) {
                $("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal');   // loads the page into 'min-content' section
            }
            else {
                // display error message
            }

No, the other way around. How to retrieve the data from the form (json).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM