insert Data in DataBase using Ajex BeginForm in MVC
View Code :
@model Ajex_MVC.Models.MyCroud
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<div id="LodingImg" style="display:none">
<img src="~/Content/img/Loading.jfif" height="100" width="100" />
</div>
<div id="DivForUpdate">
</div>
@using (Ajax.BeginForm("Create", "Home",
new AjaxOptions() {
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "DivForUpdate",
LoadingElementId = "LodingImg",
LoadingElementDuration = 1000,
Confirm = "Are you sure to Login !!!!!!!!!",
OnComplete = "clear",
}))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control",id="userNametxt" } })
@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", id="passwordtxt" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
function clear() {
document.getElementById("userNametxt").value = "";
document.getElementById("passwordtxt").value = "";
}
</script>
<script src="~/Scripts/jquery-1.8.0.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
Controller Code:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(MyCroud md )
{
if (ModelState.IsValid)
{
tbl_Data tb = new tbl_Data();
tb.UserName = md.UserName;
tb.Password = md.Password;
tb.id = md.id;
db.tbl_Data.Add(tb);
int a = db.SaveChanges();
if(a==1)
{
return JavaScript("alert('Data inserted')");
}
else
{
return JavaScript("alert('Data Not inserted')");
}
}
return View();
}
Model Code :
public int id { get; set; }
[Required(ErrorMessage ="Pleas Enter user name")]
public string UserName { get; set; }
[Required(ErrorMessage ="Pleace Enter Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
Comments
Post a Comment