Example E3998
Visible to All Users

Grid View for ASP.NET MVC- How to Specify a Custom Edit Form Template

This example demonstrates how to specify a custom EditForm template in the grid, add the Upload control to the template, and edit the in-memory data source.

Grid View for MVC - CustomEditFormTemplate

Set up the grid control, set the GridView.SettingsEditing.Mode property to EditFormAndDisplayRow, create a templated column, and call the GridViewSettings.SetEditFormTemplateContent method to define an edit form template.

XML
@Html.DevExpress().GridView( settings => { settings.Name = "gridView"; settings.KeyFieldName = "ID"; settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" }; settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow; // ... settings.SetEditFormTemplateContent( c => { // ... } } ).Bind(Model).GetHtml()

Add the Upload control to the edit form template and define its settings. To allow the control to post selected files, wrap it in a form. In the FileUploadComplete event handler, assign the value obtained from the server to the text box editor.

XML
@Html.DevExpress().GridView( settings => { // ... settings.SetEditFormTemplateContent( c => { // ... using(Html.BeginForm("ImageUpload", "Home", FormMethod.Post)) { Html.DevExpress().UploadControl( ucSettings => { // ... ucSettings.ClientSideEvents.FileUploadComplete = "function(s, e) { if(e.isValid) { avatarUrl.SetValue(e.callbackData) } }"; } ).Render(); } Html.DevExpress().TextBox( edtSettings => { edtSettings.Name = "avatarUrl"; edtSettings.Width = System.Web.UI.WebControls.Unit.Percentage(100); } ) } } ).Bind(Model).GetHtml()

Update the in-memory data source.

Files to Look At

Documentation

More Examples

Does this example address your development requirements/objectives?

(you will be redirected to DevExpress.com to submit your response)

Example Code

Sample/Controllers/HomeController.cs(vb)
C#
using System; using System.IO; using System.Web; using System.Web.Mvc; using System.Web.UI; using DevExpress.Web; using DevExpress.Web.Mvc; using Sample.Models; namespace Sample.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(UserProvider.Select()); } public ActionResult GridViewPartial() { return PartialView(UserProvider.Select()); } [HttpPost, ValidateInput(false)] public ActionResult AddNew([ModelBinder(typeof(DevExpressEditorsBinder))] User user) { if(ModelState.IsValid) UserProvider.Insert(user); else ViewData["UserInfo"] = user; return PartialView("GridViewPartial", UserProvider.Select()); } [HttpPost, ValidateInput(false)] public ActionResult Update([ModelBinder(typeof(DevExpressEditorsBinder))] User user) { if(ModelState.IsValid) UserProvider.Update(user); else ViewData["UserInfo"] = user; return PartialView("GridViewPartial", UserProvider.Select()); } [HttpPost, ValidateInput(false)] public ActionResult Delete([ModelBinder(typeof(DevExpressEditorsBinder))] User user) { UserProvider.Delete(user); return PartialView("GridViewPartial", UserProvider.Select()); } public ActionResult ImageUpload() { UploadControlExtension.GetUploadedFiles("uploadControl", UploadControlHelper.ValidationSettings, UploadControlHelper.uploadControl_FileUploadComplete); return null; } } public class UploadControlHelper { public static readonly UploadControlValidationSettings ValidationSettings = new UploadControlValidationSettings { AllowedFileExtensions = new string[] { ".jpg", ".jpeg", ".jpe"}, MaxFileSize = 4000000 }; public static void uploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e) { if(e.UploadedFile.IsValid) { string resultFilePath = "~/Content/Avatars/" + string.Format("Avatar{0}{1}", Convert.ToString(HttpContext.Current.Session["UserID"]), Path.GetExtension(e.UploadedFile.FileName)); e.UploadedFile.SaveAs(HttpContext.Current.Request.MapPath(resultFilePath)); IUrlResolutionService urlResolver = sender as IUrlResolutionService; if(urlResolver != null) e.CallbackData = urlResolver.ResolveClientUrl(resultFilePath) + "?refresh=" + Guid.NewGuid().ToString(); } } } }
Sample/Views/Home/GridViewPartial.cshtml
Razor
@model List<Sample.Models.User> @Html.DevExpress().GridView( settings => { settings.Name = "gridView"; settings.KeyFieldName = "ID"; settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" }; settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow; settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "AddNew" }; settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "Update" }; settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "Delete" }; settings.CommandColumn.Visible = true; settings.CommandColumn.NewButton.Visible = true; settings.CommandColumn.DeleteButton.Visible = true; settings.CommandColumn.EditButton.Visible = true; settings.Columns.Add("NickName"); settings.Columns.Add( column => { column.Caption = "Avatar"; column.HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; column.SetDataItemTemplateContent(c => { string url = (string)DataBinder.Eval(c.DataItem, "AvatarUrl"); ViewContext.Writer.Write( !string.IsNullOrEmpty(url) ? "<img src=\"" + Url.Content(url) + "\"/>" : "<center>Click Edit to load a New Avatar</center>" ); }); } ); settings.SetEditFormTemplateContent( c => { var user = ViewData["UserInfo"] != null ? ViewData["UserInfo"] : c.DataItem; Session["UserID"] = DataBinder.Eval(user, "ID") != null ? DataBinder.Eval(user, "ID") : Model.Count + 1; ViewContext.Writer.Write("<div style=\"padding: 4px 0px; font-size: 8pt\">"); Html.DevExpress().Label( edtSettings => { edtSettings.Text = "NickName"; edtSettings.AssociatedControlName = "NickName"; edtSettings.ControlStyle.Font.Bold = true; } ).Render(); Html.DevExpress().TextBox( edtSettings => { edtSettings.Name = "NickName"; edtSettings.ShowModelErrors = true; edtSettings.Width = System.Web.UI.WebControls.Unit.Pixel(200); } ) .Bind(DataBinder.Eval(user, "NickName")) .Render(); ViewContext.Writer.Write("</div>"); ViewContext.Writer.Write("<div style=\"padding: 4px 0px; font-size: 8pt\">"); Html.DevExpress().Label( edtSettings => { edtSettings.Text = "Avatar"; edtSettings.ControlStyle.Font.Bold = true; } ).Render(); ViewContext.Writer.Write("<br />"); ViewContext.Writer.Write( "<div style=\"margin-top: 2px\">" + "Allowed ContentTypes: image/jpeg<br />" + "Maximum File Size: 4Mb" + "</div>" ); ViewContext.Writer.Write("<br />"); using(Html.BeginForm("ImageUpload", "Home", FormMethod.Post)) { Html.DevExpress().UploadControl( ucSettings => { ucSettings.Name = "uploadControl"; ucSettings.ShowUploadButton = true; ucSettings.AddUploadButtonsSpacing = 0; ucSettings.AddUploadButtonsHorizontalPosition = AddUploadButtonsHorizontalPosition.InputRightSide; ucSettings.CallbackRouteValues = new { Controller = "Home", Action = "ImageUpload" }; ucSettings.ValidationSettings.Assign(Sample.Controllers.UploadControlHelper.ValidationSettings); ucSettings.ClientSideEvents.FileUploadComplete = "function(s, e) { if(e.isValid) { avatarUrl.SetValue(e.callbackData) } }"; } ).Render(); } Html.DevExpress().Label( edtSettings => { edtSettings.Text = "Avatar Url:"; edtSettings.AssociatedControlName = "avatarUrl"; } ).Render(); Html.DevExpress().TextBox( edtSettings => { edtSettings.Name = "avatarUrl"; edtSettings.Width = System.Web.UI.WebControls.Unit.Percentage(100); } ) .Bind(DataBinder.Eval(user, "AvatarUrl")) .Render(); ViewContext.Writer.Write("</div>"); ViewContext.Writer.Write( "<div style=\"text-align: right; padding: 2px 2px 2px 2px\">" + string.Format("<a href=\"#\" onclick=\"{0}.UpdateEdit()\">Update</a>&nbsp;", settings.Name) + string.Format("<a href=\"#\" onclick=\"{0}.CancelEdit()\">Cancel</a>", settings.Name) + "</div>" ); } ); } ).Bind(Model).GetHtml()
Sample/Models/Users.cs(vb)
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web; using System.Web.SessionState; namespace Sample.Models { public class User { int id; string nickname; string avatarUrl; public User() { ID = 0; NickName = string.Empty; AvatarUrl = string.Empty; } [Key] public int ID { get { return id; } set { id = value; } } [Required(ErrorMessage = "NickName is required")] public string NickName { get { return nickname; } set { nickname = value; } } public string AvatarUrl { get { return avatarUrl; } set { avatarUrl = value; } } public void Assign(User source) { NickName = source.NickName; AvatarUrl = source.AvatarUrl; } } public static class UserProvider { const string Key = "UserProvider"; static HttpSessionState Session { get { return HttpContext.Current.Session; } } static List<User> Data { get { if(Session[Key] == null) Restore(); return Session[Key] as List<User>; } } public static IEnumerable<User> Select() { return Data; } public static void Insert(User item) { item.ID = Data.Count + 1; Data.Add(item); } public static void Update(User item) { User storedItem = FindItem(item.ID); storedItem.Assign(item); } public static void Delete(User item) { User storedItem = FindItem(item.ID); Data.Remove(storedItem); } public static void Restore() { Session[Key] = new List<User>(); } static User FindItem(int id) { foreach(User item in Data) { if (item.ID == id) return item; } return null; } } }

Disclaimer: The information provided on DevExpress.com and affiliated web properties (including the DevExpress Support Center) is provided "as is" without warranty of any kind. Developer Express Inc disclaims all warranties, either express or implied, including the warranties of merchantability and fitness for a particular purpose. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.

Confidential Information: Developer Express Inc does not wish to receive, will not act to procure, nor will it solicit, confidential or proprietary materials and information from you through the DevExpress Support Center or its web properties. Any and all materials or information divulged during chats, email communications, online discussions, Support Center tickets, or made available to Developer Express Inc in any manner will be deemed NOT to be confidential by Developer Express Inc. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.