Home > Enterprise >  Using Json.stringify in controller in asp .net MVC
Using Json.stringify in controller in asp .net MVC

Time:08-29

I have written this part of ajax code to post some information that will be updated in the database.

function postUpdateList() {
    var id = $('#Id').val();
    $.ajax({
        url: `Home/EditPost/${id}`,
        type:'POST',
        contentType:"application/json;charset=utf-8",
        dataType: JSON.stringify({ "Name": $('#name').val(), "Father": $('#father').val(), "Mother": $('#mother').val(), "Age": $('#age').val(), "Email": $('#email').val(), "Phone": $('#phone').val(), "Standard": $('#standard').val(), "Section": $('#section').val() }),
        success: function (data) {
            alert(data);
        }
    });
}

Now how can I receive this Json.stringify object in my controller and update the information in the database? This is my controller method:-

[HttpPost]
public JsonResult EditPost(int ID)
{ 
     var data = "Updated SUccesfully";
     return Json(data);
}

CodePudding user response:

Have the same idea as others, you need to modify the POST action which is expected to receive the ID from the URL, and the EditPostModel object from the request body.

[HttpPost]
public JsonResult EditPost(int ID, EditPostModel model)
{
    var data = "Updated SUccesfully";
    return Json(data);
}
public class EditPostModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Father { get; set; }
    public string Mother { get; set; }
    public int Age { get; set; }
    // Following property
}

While there are some errors in the JavaScript part,

  1. The url needs a leading slash.

    • Hence it will send the request to http://<your-domain>/Home/Post/{id}.
    • Without leading slash, the request will be sent to http://<your-domain>/Home/Post/{id}/Home/Post/{id} which is incorrect.
    • Reference: enter image description here

      CodePudding user response:

      what your controller receives with this request is a json object,

      which represents a model. (Check your browsertools for the structure)

      Therefore the best option would be to add [FromBody] YourRequestModel model as a paramter on your action.

      CodePudding user response:

      You have to create a special class for your data and use FromBody attribute in your controller action, also add ID attribute routing

      [HttpPost("{ID}")]
      public JsonResult EditPost(int ID, [FromBody] List<StudentModel>  data)
            return Json(data);
      
  • Related