简体   繁体   中英

how to return MVC modal in JsonResult in Ajax call?

How to return MVC model in JsonResult in Ajax call? in below example in I can return contact object with result and catch that in ajax success callback.

C#

  [HttpPost]
    public JsonResult Index(Contact contact)
    {
        if (ModelState.IsValid)
        {
           //send contact object with result

           var result = new { Success = "true", Message = "No Error" };
           return Json(result, JsonRequestBehavior.DenyGet);

        }
        else
        {
            var result = new { Success = "false", Message = "Invalid state" };
            return Json(result, JsonRequestBehavior.DenyGet);
        }
    }

JavaScript

 $.ajax({
            url: this.action,
            type: 'POST',
            data: formData,
            mimeType: "multipart/form-data",
            contentType: false,
            cache: false,
            processData: false,
            success: function (result) {
                var obj = jQuery.parseJSON(result);
               //need to access contact data here.
              updateSuccess(obj);

            },
            error: function(jqXHR, textStatus, errorThrown) {
                //alert("Fail");

            }
        });

If you need to return the Contact object, then return it. Something like this:

return Json(contact, JsonRequestBehavior.DenyGet);

Then in your JavaScript:

success: function (result) {
    var obj = jQuery.parseJSON(result);
    // obj is an instance of Contact, at least in terms of the DTO data expressed in JSON
}

If you need to return both, then just add it as part of the anonymous type:

var result = new { Success = "true", Message = "No Error", Contact = contact };
return Json(result, JsonRequestBehavior.DenyGet);

Then in your JavaScript:

success: function (result) {
    var obj = jQuery.parseJSON(result);
    // obj.Contact is an instance of Contact, at least in terms of the DTO data expressed in JSON
    updateSuccess(obj);
}

Of course, it's also worth noting that unless your server-side code is modifying the Contact in some way, you're just returning something that the client-side code sent in the first place. Which means it's already available client-side in some way, basically in the formData object. So you might not need to return it (unless there's more going on here that you removed from the example).

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