This blog we discuss how to insert data with validation using mvc
4.
First create a Table like Insertdata
(EmpId int ,Identity ,Not null,
Name varchar(50),
City varchar(50),
Course varchar(50)
)
Create an entity framework like
insdataentity
Model Class:-
Ins.cs
public class ins
{
[Required(ErrorMessage="Enter
a valid Empid")]
public int EmpId { get; set; }
[Required(ErrorMessage = "Enter
a valid Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Enter
a valid City")]
public string City { get; set; }
[Required(ErrorMessage = "Enter
a valid Course Name")]
public string Course { get; set; }
}
Controller Class:-
public class InsmydataController : Controller
{
//
// GET:
/Insdata/
insdatapromvcEntities insins = new insdatapromvcEntities();
public ActionResult Insert()
{
return View();
}
[HttpPost]
public ActionResult Insert(ins myins)
{
if (ModelState.IsValid)
{
try
{
insdata sanins = new insdata();
sanins.Name = myins.Name;
sanins.City = myins.City;
sanins.Course =
myins.Course;
insins.insdatas.Add(sanins);
insins.SaveChanges();
ViewBag.mymsg = "Successfully insert data";
}
catch (Exception ex)
{
return View("Error in the page");
}
ModelState.Clear();
}
return View();
}
}
}
View model:-
@model
sanaprilmvc.Models.ins
@{
ViewBag.Title = "Insert";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Insert</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>ins</legend>
<div style="text-align:center;background-color:gray;">
<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>
<div class="editor-label">
@Html.LabelFor(model => model.Course)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Course)
@Html.ValidationMessageFor(model => model.Course)
</div>
<p>
@* <input type="image" value="Submit"
src="~/Images/submit.png" width="20" height="20"
/>*@
<input type="submit" value="Submit" />
</p>
</div>
<p>@ViewBag.mymsg</p>
</fieldset>
}
<div>
@Html.ActionLink("Back
to List", "Index")
</div>
@section
Scripts {
@Scripts.Render("~/bundles/jqueryval")
}