Without knowing your setup or your current level understanding of MVC, I can only share a general approach. Coming from Web Forms to MVC requires a paradigmn shift which in the end will make you a better programmer.
First you install Entity Framework in your project through NuGet.
Next, you create a Model which contains every field you require for the entity. In this example, I will call it "Member" with an Id, Name, Email, and Address:
public sealed class Member
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
}
By making your field of type "int" and naming it "Id" Entity Framework will automatically make that field a PRIMARY KEY and an AUTO NUMBER without you having to configure anything.
Next, you add this entity to the ApplicationDbContext class:
public DbSet<Member> Members { get; set; }
As it's often the case in real projects, your form will only collect SOME of the fields in your entity. In this example I want to collect only Name and Email and leave the address to be filled out by the user later. For that, you create a View Model that will be responsible for collecting just the data you want the user to provide. To keep things nice and organized, I would create a separate folder called "ViewModels" and keep all my view models in there:
public sealed class MemberViewModel
{
public int? Id { get; set;}
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
By making the Id nullable in your view model, you can use the same
view model for either creating a new member or updating an existing
member.
Also, as a rule of thumb, decorate your view models with Data Annotations for validation purposes.
It is the responsibility of your view models to validate data before
passing it to the entity models and NOT the entity models themselves.
Why? Separation of concerns: an important practice that is often
ignored in Web Forms programming.
Go to your view (which should be named InsertDetail) and at the top of the view add the View Model:
@model ViewModel.MemberViewModel
Now you have created a strongly typed view based on your view model. Although not required, you can now add the fields to your view using HTML helpers like so:
@Html.TextBoxFor(m => m.Email, new { @class = "form-control", autofocus = "", placeholder = "Email" })
You may also decide to add the Id using a hidden field, but if you are using the form just to insert data into the table, it's best to leave the Id field out because this will cause its value to be NULL. However if you decide to add the Id as a hidden field you do it this way:
@Html.HiddenFor(m => m.Id)
To display validation errors at the top of the page, add the following inside your "form" tag or BeginForm HTML helper but before any form fields:
@Html.ValidationSummary("", new { @class = "text-danger" })
To prevent form spoofing from hackers add this line before the validation summary:
@Html.AntiForgeryToken()
Now go to your controller. You don't need to redirect anywhere else to carry out the insertion process. You can handle everything in your controller.
public ActionResult InsertDetail(MemberViewModel model)
{
if (ModelState.IsValid)
{
// Get context (this should be done through a repository but let's focus)
using (var ctx = new ApplicationDbContext())
{
var member = new Member();
if (model.Id == null)
{
// Insert Member
member.Name = model.Name;
member.Email = model.Email;
ctx.Members.Add(member);
}
else
{
// Check if Id already exists
int memberId = 0;
bool result = int.TryParse(model.Id.ToString(), out memberId);
member = ctx.Members.FirstOrDefault(x => x.Id == memberId);
if (member != null) // this member already exists
{
// You can decide to throw an error or update the entity. Let's throw error
ModelState.AddModelError("", "Member Already Exists");
return View(model);
}
}
}
}
// If you get here then there is a validation error
return View(model);
}
InsertDetail()and stay on Insert view if there is already a detail with the same Id and just show an alert message over Insert view?ViewBagis pointless (that is for passing data from a controller to a view). If you want to stay on the same page, then add aModelStateErrorand return the view.