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);
}
3
Answers
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.You have to create a special class for your data and use FromBody attribute in your controller action, also add ID attribute routing
Have the same idea as others, you need to modify the POST action which is expected to receive the
ID
from the URL, and theEditPostModel
object from the request body.While there are some errors in the JavaScript part,
The
url
needs a leading slash.http://<your-domain>/Home/Post/{id}
.http://<your-domain>/Home/Post/{id}/Home/Post/{id}
which is incorrect.Use
data
to pass the data, notdataType
.dataType
specifies the form of data response returned from the server.