📜 ⬆️ ⬇️

In-line editing tabular data in ASP.Net MVC 3

I present to your attention one more implementation of AjaxGrid on ASP.Net MVC 3.
The article describes how to create a tabular form with inline editing, ajax sorting and ajax pager.

This implementation is a compilation of several available components.
As is usually the case, I needed to display the table data with the possibility of editing it for work purposes. Approximately as in the screenshot:

Desired result

Before we start installing AjaxGridScaffolder
PM> Install-Package AjaxGridScaffolder

')

Create a data layer



Essence
 namespace HabrahabrMVC.Domain.Entities { public class RealtyObject { public int Id { get; set; } public string City { get; set; } public string Street { get; set; } public string House { get; set; } public double Cost { get; set; } public bool Visible { get; set; } } } 

Interface.
 namespace HabrahabrMVC.Domain.Abstract { public interface IRepository { IQueryable<RealtyObject> GetAll(); void Save(RealtyObject objectToSave); } } 

Context.
 namespace HabrahabrMVC.Domain.Concrete { public class EFContext : DbContext { public DbSet<RealtyObject> RealtyObjects { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } } 

Interface implementation.
 namespace HabrahabrMVC.Domain.Concrete { public class EFRepository :IRepository { EFContext _db = new EFContext(); public void Save(Entities.RealtyObject objectToSave) { _db.Entry(_db.RealtyObjects.SingleOrDefault(z=>z.Id==objectToSave.Id)).CurrentValues.SetValues(objectToSave); _db.Entry<RealtyObject>(_db.RealtyObjects.SingleOrDefault(z => z.Id == objectToSave.Id)).State = System.Data.EntityState.Modified; _db.SaveChanges(); } public IQueryable<RealtyObject> GetAll() { return _db.RealtyObjects.AsQueryable(); } } } 

Create a controller


ObjectsView:
Creating a controller
1) To do this, right-click in the Object Explorer'e (Object Explorer) on the Controllers folder, select Add-> Controller ... (Add-> Controller ...).
2) We write the name ObjectsViewController.
3) Template - Ajax Grid Controller
4) Model class - RealtyObject (HabraHabrMVC3.Domain.Entities)
5) Data context class - EFContext (HabraHabrMVC3.Domain.Concrete)
6) Add.

After the wizard has generated the code, we add a constructor to the controller, so that Ninject correctly injects our data layer.
 //private EFContext db = new EFContext(); private IRepository db; public ObjectsViewController(IRepository dbparam) { db = dbparam; } 


Now it is necessary to change the data sources in the generated code:
db.RealtyObjects on db.GetAll ()
db.RealtyObjects.Find (id) on db.GetAll (). SingleOrDefault (z => z.Id == id)

Now I don’t need actions to create, edit and delete data, I’ll delete them.
Also in the view GridData.cshtml deleted the edit and delete buttons.

Now the line does not work:
 ObjectQuery<RealtyObject> realtyobjects = (db as IObjectContextAdapter).ObjectContext.CreateObjectSet<RealtyObject>(); 

because db does not support IObjectContextAdapter.
Therefore, we add the Linq extension method.

I created a separate static class OrderByHelper.
 namespace HabraHabrMVC3.Infrastructure { public static class OrderByHelper { public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> enumerable, string orderBy) { return enumerable.AsQueryable().OrderBy(orderBy).AsEnumerable(); } public static IQueryable<T> OrderBy<T>(this IQueryable<T> collection, string orderBy) { foreach (OrderByInfo orderByInfo in ParseOrderBy(orderBy)) collection = ApplyOrderBy<T>(collection, orderByInfo); return collection; } private static IQueryable<T> ApplyOrderBy<T>(IQueryable<T> collection, OrderByInfo orderByInfo) { string[] props = orderByInfo.PropertyName.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach (string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); string methodName = String.Empty; if (!orderByInfo.Initial && collection is IOrderedQueryable<T>) { if (orderByInfo.Direction == SortDirection.Ascending) methodName = "ThenBy"; else methodName = "ThenByDescending"; } else { if (orderByInfo.Direction == SortDirection.Ascending) methodName = "OrderBy"; else methodName = "OrderByDescending"; } //TODO: apply caching to the generic methodsinfos? return (IOrderedQueryable<T>)typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] { collection, lambda }); } private static IEnumerable<OrderByInfo> ParseOrderBy(string orderBy) { if (String.IsNullOrEmpty(orderBy)) yield break; string[] items = orderBy.Split(','); bool initial = true; foreach (string item in items) { string[] pair = item.Trim().Split(' '); if (pair.Length > 2) throw new ArgumentException(String.Format("Invalid OrderBy string '{0}'. Order By Format: Property, Property2 ASC, Property2 DESC", item)); string prop = pair[0].Trim(); if (String.IsNullOrEmpty(prop)) throw new ArgumentException("Invalid Property. Order By Format: Property, Property2 ASC, Property2 DESC"); SortDirection dir = SortDirection.Ascending; if (pair.Length == 2) dir = ("desc".Equals(pair[1].Trim(), StringComparison.OrdinalIgnoreCase) ? SortDirection.Descending : SortDirection.Ascending); yield return new OrderByInfo() { PropertyName = prop, Direction = dir, Initial = initial }; initial = false; } } private class OrderByInfo { public string PropertyName { get; set; } public SortDirection Direction { get; set; } public bool Initial { get; set; } } private enum SortDirection { Ascending = 0, Descending = 1 } } } 


And then a new kind of action GridData:

 public ActionResult GridData(int start = 0, int itemsPerPage = 20, string orderBy = "Id", bool desc = false) { Response.AppendHeader("X-Total-Row-Count", db.GetAll().Count().ToString()); var realtyobjects = db.GetAll().OrderBy(orderBy + (desc ? " desc" : "")); return PartialView(realtyobjects.Skip(start).Take(itemsPerPage)); } 


Now we have a great Ajax table with sorting and paging.

Adding inline editing



Add another extension method, only for the HTML helper:

 namespace System.Web { public static class HtmlPrefixScopeExtensions { private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_"; public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName) { var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName); string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString(); // autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync. html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex))); return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex)); } public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix) { return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix); } private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName) { // We need to use the same sequence of IDs following a server-side validation failure, // otherwise the framework won't render the validation error messages next to each item. string key = idsToReuseKey + collectionName; var queue = (Queue<string>)httpContext.Items[key]; if (queue == null) { httpContext.Items[key] = queue = new Queue<string>(); var previouslyUsedIds = httpContext.Request[collectionName + ".index"]; if (!string.IsNullOrEmpty(previouslyUsedIds)) foreach (string previouslyUsedId in previouslyUsedIds.Split(',')) queue.Enqueue(previouslyUsedId); } return queue; } private class HtmlFieldPrefixScope : IDisposable { private readonly TemplateInfo templateInfo; private readonly string previousHtmlFieldPrefix; public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix) { this.templateInfo = templateInfo; previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix; templateInfo.HtmlFieldPrefix = htmlFieldPrefix; } public void Dispose() { templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix; } } } } 


Replace view GridData with
 @model IEnumerable<HabraHabrMVC3.Domain.Entities.RealtyObject> @if (Model.Count() > 0) { foreach (var item in Model) { <text>@Html.Partial("Edit", item)</text> } } 


And view Edit at:
 @model HabraHabrMVC3.Domain.Entities.RealtyObject @using (Html.BeginCollectionItem("objects")) { <tr> <td> @Html.EditorFor(model => model.City) @Html.ValidationMessageFor(model => model.City) </td> <td> @Html.EditorFor(model => model.Street) @Html.ValidationMessageFor(model => model.Street) </td> <td> @Html.EditorFor(model => model.House) @Html.ValidationMessageFor(model => model.House) </td> <td> @Html.EditorFor(model => model.Cost) @Html.ValidationMessageFor(model => model.Cost) </td> <td> @Html.EditorFor(model => model.Visible) @Html.ValidationMessageFor(model => model.Visible) </td> </tr> } 


In the view index add:
 @using (Html.BeginForm("Save", "ObjectsView", FormMethod.Post)) { <table id="AjaxGrid"> ...code... </table> <input type="submit" id="save" value="" /> } 


Add action Save:
 [HttpPost] public ActionResult Save(ICollection<RealtyObject> objects) { foreach(var item in objects) { db.Save(item); } return RedirectToAction("Index"); } 

Here it is important that the collection name in @using (Html.BeginCollectionItem (" objects ")) matches the name of the parameter in the action Save method (ICollection objects ).

Everything, it turned out a tabular form with inline editing, ajax sorting and ajax pager.

The list of used literature on the Internet:

1) Ajax Grid Scaffolder

2) Editing a variable length list, ASP.NET MVC 2-style

3) Dynamic SQL-like Linq OrderBy Extension

Download the result.

Source: https://habr.com/ru/post/138580/


All Articles