Model Class:
public class RegionViewModel{
public int Id { get; set; }
public string Name { get; set; }
}
Controller:
[HttpPost]public async Task<ActionResult> AddOrUpdate([Bind(Include = "Name,Id")] RegionViewModel model)
{
//do your stuff
return Json(result, JsonRequestBehavior.AllowGet);
}
HTML or CShtml View:
@using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "Region" })){
@Html.TextFor(m => m.Id, new { })
@Html.TextFor(m => m.Name, new { })
}
<script>
//Add or update
$("form#Region").off("submit").on("submit", function (e) {
e.preventDefault();
try {
var form = $("form#Region");
$.ajax(
{
url: "../Region/AddOrUpdate",
// dataType: "json",
method: "POST",
data: JSON.stringify($(form).serializeObject()),
contentType: "application/json",
processData: false,
success: function (response) {
//do your stuff on success
},
error: function (jqXhr, textStatus, errorThrown) {
alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
},
complete: function () {
//do your stuff on success
}
});
}
catch (ex) {
alert(ex);
}
});
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
No comments:
Post a Comment