Hi dear
This blog I will writing insert data code in mvc using jquery
Controller:-
public class JqueryTestController : Controller
{
//
// GET:
/JqueryTest/
public ActionResult Save()
{
return View();
}
[HttpPost]
public ActionResult Save(MyAjax insit)
{
string message = "";
if (ModelState.IsValid)
{
try
{
using (JqueryNowTestEntities dc = new JqueryNowTestEntities())
{
dc.MyAjaxes.Add(insit);
dc.SaveChanges();
message = "Successfully saved";
}
}
catch (Exception ex)
{
message = "error ! plz try again";
}
}
else
{
message = "plz provide correct data";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return View(insit);
}
//
return View(insit);
}
}
}
View
page code:-
@model
SanPracticeMvc.MyAjax
@{
ViewBag.Title = "Save";
}
<h2>Save</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>MyAjax</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<p>
<input type="submit" value="Save" id="MySave" />
</p>
<div id="content">
</div>
</fieldset>
}
<div>
@Html.ActionLink("Back
to List", "Index")
</div>
@section
Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function(){
$("#MySave").click(function(){
$("#content").html("<b>plz
wait ...</b>");
var dataobject ={
Name : $("#Name").val(),
City : $("#City").val()
};
$.ajax({
url: "@Url.Action("Save","JqueryTest")",
type:"POST",
data:dataobject,
dataType:"json",
success: function(data){
if(data.toString() =="Successfully saved"){
$("#Name").val('');
$("#City").val('');
$("#content").html("<div> + data +</div>");
}
else{
$("#content").html("<div> + data +</div>");
}
},
error: function(){
$("#content").html("<div> error ! plz try again</div>");
}
});
});
});
</script>
No comments:
Post a Comment