How to Use ASP.NET MVC Scaffolding in MVC Edition

If you're coming from a Web Forms or LightSwitch background, then you've probably noticed that, without the controls and designers that make configuration easy, designing apps in MVC requires some extra effort. With our recent release of MVC scaffolding for FlexGrid and Input controls, you'll find that creating views with ComponentOne MVC Edition controls is a breeze.

What is MVC Scaffolding?

Scaffolding is a code-generation framework for ASP.NET web applications that allows developers to quickly generate views and controllers based on the model present in the application. Using scaffolding, you can create code-free views and save considerable time.

MVC Edition Scaffolders

C1Studio MVC Edition includes scaffolding for FlexGrid and Input controls. These scaffolders get installed when you install MVC Edition from the installer. They're supported in Visual Studio 2015 and 2013, and if you're using ASP.NET Core, the scaffolders use TagHelpers syntax automatically. Let's walk through how to get started with the scaffolders.

How to use the FlexGrid Scaffolder

Step One: Create Project

When you create a new project using C1MVC Template, use the standard Visual Studio template to create the MVC project. Using the C1 templates has the advantage of preconfigured references and resources.

Step Two: Add Entity Framework Data Model

  1. Add an Entity Framework model to the project. (This example use the Northwind database).
  2. Save and rebuild the project.

Step Three: Initialize Scaffolder

  1. Right-click controllers and click Add New Scaffolded Item.
  2. In the Add Scaffold wizard, select Common.
  3. Select C1Scaffolder.
  4. Click Add.

Initialise FlexGrid Scaffolder

Select FlexGrid control and click Next. Add FlexGrid Control in MVC Wizard

Configure Controller

In the General tab, specify the model as follows:

  1. Fill in the Controller Name and View Name.
  2. Select Model Class from the drop-down list. The list shows all the available model types in the application in addition to the NWind.edmx model added in Step 1. In our case, we select Customers to populate customers in the FlexGrid.
  3. Select Data Context Class from the drop-down list. In our case, we select NorthwindEntities. FlexGrid Scaffolder

Configure FlexGrid

Go to the Columns tab to specify the columns in the FlexGrid control. By default, Auto Generate Columns is checked; if not, then you can add, delete, or move columns upward or downward in the sequence in which they should appear in the final view. In our case, we have selected columns as shown in the following image: Screen3

Set Additional Features

  • Go to the Editing tab and check Allow Edit and Allow Delete checkboxes.
  • Go to Grouping tab. In the Group Settings, check Show Groups and Show Groups checkboxes from Show Groups.
  • Go to Show Groups tab and check Show Groups checkbox. Let the other settings be same as default.
  • Go to Show Groups tab and view the defaults; both Allow Sorting and Show Sort checkboxes should be checked.
  • If you need to subscribe to any client side method, go to the Client Events tab and check the relevant client method checkbox.

Finish

Click Add. This generates the code for required controller methods and Views Razor syntax.

Generated Code

Controller Code


public partial class CustomersController : Controller  
{  
private C1MvcWebApplication3.NorthwindEntities db = new C1MvcWebApplication3.NorthwindEntities();  
public ActionResult Index()  
{  
var model = db.Customers;  
return View(model);  
}  

public ActionResult GetCustomers([C1JsonRequest] CollectionViewRequest requestData)  
{  
return this.C1Json(CollectionViewHelper.Read(requestData, db.Customers));  
}  

public ActionResult FlexGrid_Update([C1JsonRequest]CollectionViewEditRequest requestData)  
{  
return Update(requestData, db.Customers);  
}  

private ActionResult Update(CollectionViewEditRequest requestData, DbSet data) where T : class  
{  
return this.C1Json(CollectionViewHelper.Edit(requestData, item =>  
{  
string error = string.Empty;  
bool success = true;  
try  
{  
db.Entry(item as object).State = EntityState.Modified;  
db.SaveChanges();  
}  
catch (DbEntityValidationException e)  
{  
error = string.Join(",", e.EntityValidationErrors.Select(result =>  
{  
return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage));  
}));  
success = false;  
}  
catch (Exception e)  
{  
error = e.Message;  
success = false;  
}  
return new CollectionViewItemResult  
{  
Error = error,  
Success = success && ModelState.IsValid,  
Data = item  
};  
}, () => data.ToList()));  
}  

public ActionResult FlexGrid_Delete([C1JsonRequest]CollectionViewEditRequest requestData)  
{  
return Delete(requestData, db.Customers, item => new object[] { item.CompanyName });  
}  

private ActionResult Delete(CollectionViewEditRequest requestData, DbSet data, Func<T, object[]> getKeys) where T : class  
{  
return this.C1Json(CollectionViewHelper.Edit(requestData, item =>  
{  
string error = string.Empty;  
bool success = true;  
try  
{  
var resultItem = data.Find(getKeys(item));  
data.Remove(resultItem);  
db.SaveChanges();  
}  
catch (DbEntityValidationException e)  
{  
error = string.Join(",", e.EntityValidationErrors.Select(result =>  
{  
return string.Join(",", result.ValidationErrors.Select(err => err.ErrorMessage));  
}));  
success = false;  
}  
catch (Exception e)  
{  
error = e.Message;  
success = false;  
}  
return new CollectionViewItemResult  
{  
Error = error,  
Success = success && ModelState.IsValid,  
Data = item  
};  
}, () => data.ToList()));  
}  

}  

View Code


@using C1.Web.Mvc  
@using C1.Web.Mvc.Fluent  
@using C1.Web.Mvc.Grid  
@model IEnumerable  

//   

        function formatItem(sender, e) {  
            // Implement the event handler for formatItem.  
        }  


// ]]>  

@(Html.C1().FlexGrid()  
.Id("fg")  
.Bind(bl => { bl.Bind(Url.Action("GetCustomers"))  
.Update(Url.Action("FlexGrid_Update"))  
.Delete(Url.Action("FlexGrid_Delete"))  
.GroupBy("City")  
;})  
.AllowDelete(true)  
.Filterable(f => f.DefaultFilterType(FilterType.Both)  
)  
.Height("800px")  
.OnClientFormatItem("formatItem"))  

The application is ready with a fully functional FlexGrid supporting CRUD operations. Customers Customers View the Demos >> See Documentation >>

GrapeCity

GrapeCity Developer Tools
comments powered by Disqus