Pass HTML Content from View to Controller using jQuery Ajax
Ajax means Asynchronous JavaScript and XML. It helps you to load the server data without refreshing the browser. So you can refresh part of the web page without loading the entire page. jQuery Ajax performs asynchronous Ajax requests.
The following is a view code. Here I have included the Google jQuery CDN (If you want you can download the jQuery library and include the link). Also, I have added some text boxes and textarea to collect the input values.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<table class="width-hundred-percent">
<tr>
<td> ID: </td>
<td> <input id="idTextBox" type="text" style="width:100%" /> </td>
</tr>
<tr>
<td>Subject</td>
<td><input id="subjectTextBox" type="text" style="width:100%" /></td>
</tr>
<tr>
<td valign="top">Content: </td>
<td><textarea id="contentTextArea" style="margin: 0px;width: 500px;height: 300px;"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="right"> <button id="saveButton">Save</button></td>
</tr>
</table>
Here I'm going to pass the values using the complex parameter. So I have created a class called ContentModel.
public class ContentModel
{
public int ID { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
}
When the event triggers, first the object will create with the input values.
The first input value is the ID integer, so it is converted to an integer using the parseInt
function. Using JSON.stringify(obj), the object is converted to a JSON string and passed to the /Home/Save controller action
The first input value is the ID integer, so it is converted to an integer using the parseInt
function. Using JSON.stringify(obj), the object is converted to a JSON string and passed to the /Home/Save controller action
<script>
$("#saveButton").click(function () {
obj = {
ID: parseInt($("#idTextBox").val()),
Subject: $("#subjectTextBox").val(),
Content: $("#contentTextArea").val()
};
$.ajax({
url: '/Home/Save',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: JSON.stringify(obj),
cache: false,
success: function () {
alert("Saved");
},
error: function () {
alert("Error");
}
});
});
</script>
The below one is controller code. In the Save action [FromBody] is added to the parameter, so it will take the parameters from the body of the HTTP request.
public IActionResult Index()
{
return View();
}
public IActionResult Save([FromBody]ContentModel content)
{
return View(content);
}
The following is a screenshot of the code above.
I hope this blog will help you. Keep coding
Comments
Post a Comment