Dynamic Insert / Update / Delete with WebGrid in MVC3

Using only one action Index(). That is no need to create separate (Create,Edit,Delete)Views.

I have created this application which insert/update/delete data into database and display it on webgrid.

Create new mvc3 web application.

In Models folder add new item select ‘Data’ > ‘ADO.NET Entity Data Model’ named as ‘Model1.edmx’

‘Generate from database’ select database and tables to create a connection string .

It will add all tables into Model1.edmx file.

Now we need to create DbContext for that open `Model1.edmx` right click select on ‘add code generation item’

Select code > ‘ADO.NET DbContext Generator’ named as ‘Model1.tt’

Going further add new class in to Models folder named as ‘SecurityIdentifierMappingViewModel.cs’

public class ViewModel
{
public IEnumerable MappingWebGridList { get; set; }
public Mapping MappingControls { get; set; }
public List PricingSecurities { get; set; }
public List CUSIPs { get; set; }

}

Need to create another class into Models folder named as ‘DataRepository’

in which going to write methods to populate dropdowns

public class DataRepository
{
public mydataEntities dbContext = new mydataEntities();

public List GetPricingSecurityID()
{
var pricingSecurityID = (from m in dbContext.Reporting_DailyNAV_Pricing.AsEnumerable()
select new SelectListItem
{
Text = m.PricingSecurityID.ToString(),
Value = m.PricingSecurityID.ToString()
}).AsEnumerable();

return pricingSecurityID.ToList();
}

public List GetCUSIP()
{
var cusipID = (from m in dbContext.StateStreet_DailyPosition_Second.AsEnumerable()
select new SelectListItem
{
Text = m.CUSIP.ToString(),
Value = m.CUSIP.ToString()
}).AsEnumerable();

return cusipID.ToList();
}
}

Now create HomeController.cs into folder ‘Controllers’

public class HomeController : Controller
{
//
// GET: /Home/

mydataEntities dbContext = new mydataEntities();
DataRepository objRepository = new DataRepository();

//GET

public ActionResult Index(string userAction , int id = 0)
{
var mappingobj = new SecurityIdentifierMappingViewModel();
mappingobj.MappingWebGridList = dbContext.SecurityIdentifierMappings.ToList();

if (id > 0)
{

mappingobj.MappingControls = dbContext.SecurityIdentifierMappings.Find(id);
if (userAction == “Delete”)
{
dbContext.SecurityIdentifierMappings.Remove(mappingobj.MappingControls);
dbContext.SaveChanges();
//return RedirectToAction(“Index”);
}

}
else
{
mappingobj.MappingControls = new SecurityIdentifierMapping();
mappingobj.MappingControls.PricingSecurityID = 0;
mappingobj.MappingControls.CUSIP = string.Empty;
}
mappingobj.PricingSecurities = objRepository.GetPricingSecurityID();
mappingobj.CUSIPs = objRepository.GetCUSIP();

return View(mappingobj);
}

//POST

[HttpPost]
public ActionResult Index(SecurityIdentifierMappingViewModel objModel)
{

//edit code

if (objModel.MappingControls.Id > 0)
{
if (ModelState.IsValid)
{
dbContext.Entry(objModel.MappingControls).State = EntityState.Modified;
try
{
dbContext.SaveChanges();
return RedirectToAction(“Index”);
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
throw;
}
}

}

//insert code
else
{
if (ModelState.IsValid)
{
dbContext.SecurityIdentifierMappings.Add(objModel.MappingControls);
try
{
dbContext.SaveChanges();
return RedirectToAction(“Index”);
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
throw;
}
}

}

objModel.MappingWebGridList = dbContext.SecurityIdentifierMappings.ToList();
objModel.PricingSecurities = objRepository.GetPricingSecurityID();
objModel.CUSIPs = objRepository.GetCUSIP();
objModel.MappingControls = new SecurityIdentifierMapping();

return View(objModel);
}
}

}

Here above there are two actions Index() 1.GET 2.POST

1.GET is used to display data into webgrid and Delete operation.

2.POST is used for Insert and Edit operations.

Now inside Views folder create Index.cshtml

@model Mapping.Models.ViewModel
@{
ViewBag.Title = “Index”;
}

Index

@*Partial control for all controls*@

@Html.Partial(“_ControlsPartial”,Model)
@Html.Partial(“_WebGridPartial”,Model.MappingWebGridList)

I have created two partial views named ‘_ControlPartial’ and ‘_WebGridPartial’ as we can use it in other Views too.

Code : _ControlPartial.cshtml

@model Mapping.Models.ViewModel
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)

Mapping

@Html.Label(“Pricing SecurityID”)
@Html.HiddenFor(model => model.MappingControls.Id)
@Html.DropDownListFor(model => model.MappingControls.PricingSecurityID,
new SelectList(Model.PricingSecurities, “Value”, “Text”),
“Select SecurityID”
)
@Html.ValidationMessageFor(model => model.MappingControls.PricingSecurityID)
@Html.Label(“CUSIP ID”)
@Html.DropDownListFor(model => model.MappingControls.CUSIP,
new SelectList(Model.CUSIPs, “Value”, “Text”),
“Select CUSIP”
)
@Html.ValidationMessageFor(model => model.MappingControls.CUSIP)
@Html.Label(“Calculation”)
@Html.TextBoxFor(model => model.MappingControls.Calculation)
@Html.ValidationMessageFor(model => model.MappingControls.Calculation)

}
@*
Can also bind with following code

@using (Html.BeginForm(“Mapping”, “Home”))
{
@Html.DropDownList(“SecurityID”, Model.PricingSecurityID, “– Select SecurityID –“)

@Html.DropDownList(“CUSIPID”, Model.PricingSecurityID, “– Select CUSIPID –“)

Map
}
*@

@model IEnumerable
@{
ViewBag.Title = “Mapping”;
WebGrid grid = null;
if (Model.Count() > 0)
{
grid = new WebGrid(source: Model,
defaultSort: “Id”,
canPage: true,
canSort: true,
rowsPerPage: 10);
}
}

Mapping Web Grid

@if (grid != null)
{
@grid.GetHtml(
tableStyle: “grid”,
headerStyle: “head”,
alternatingRowStyle: “alt”,
columns: grid.Columns(
grid.Column(“”, header: null, format: @@Html.ActionLink(“Edit”, “Index”, new { id = (int)item.id, userAction = “Edit” })
@Html.ActionLink(“Delete”, “Index”, new { id = (int)item.id, userAction=”Delete” }, new { @class = “Delete” })),
grid.Column(“PricingSecurityID”),
grid.Column(“CUSIP”),
grid.Column(“Calculation”)
)

)
}

$(function () {
$(“.Delete”).click(function () {
if (confirm(“Do you want to delete?”)) {
var href = $(“.Delete”).attr(‘href’);
href = href + “?userAction=Delete”;
window.location.href = href;
return true;
}
return false;
});
});

Thats it we are ready to F5.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s