Right now I have one value being passed and returned to a text box. I want to add multiple text boxes and pass all the values from the controller to ajax function to be displayed in the text box when the page is load.
Controller:
public string GetFormData()
{
//using Linq query and EF
Form form = db.Forms.Find(1);
if (form == null)
{
return "";
}
else
return form.username;
}
AJAX:
$("#btnSaveForm").click(function (event) {
event.preventDefault();
$('#Result2').html("<img src='/Images/loading.gif' />");
$.post($("#frmform").attr("action"), $("#frmform").serialize(), function (result) {
if (result != null) {
$('#Result2').html(result);
}
});
});
You just need to return JSON result. Consider this simple example:
Model
public class JSONTestModel
{
public string Name { get; set; }
public bool IsMarried { get; set; }
public int Age { get; set; }
}
Controller
public ActionResult TestJSON()
{
var model = new JSONTestModel()
{
Name = "John Smith",
IsMarried = true,
Age = 35
};
return View(model);
}
[HttpPost]
public ActionResult TestJSON(JSONTestModel model)
{
// YOUR CODE HERE
return Json(model);
}
Please note, the post method returns JSON result. This will serialize the object you pass to Json.
View
@using (Html.BeginForm())
{
@Html.EditorForModel()
<input id="save-data" type="button" value="Save" />
}
<script type="text/javascript">
$(function () {
$('#save-data').click(function () {
$.post($("form").attr("action"), $("form").serialize(), function (result) {
if (result != null) {
alert('Name - ' + result.Name);
alert('IsMarried - ' + result.IsMarried);
alert('Age - ' + result.Age);
}
});
});
});
</script>
The result
parameter is the json object you returned in the controller.
Hope it helps!
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.