Grid CRUD Demo


Grid crud, built using the Grid and PopupForm helpers.
There's 3 PopupForms for create, edit and delete, they are initialized via InitCrudPopupsForGrid custom helper, each PopupForm has Success js function assigned, these functions are located in Utils.js. Create post action returns the grid model for the new Item so the js func will render and append it.
Edit post action returns the item's Id and the js func is using grid.api.update to update the row, this is where the controller line:
GetItem = () => Db.Get<Dinner>(Convert.ToInt32(g.Key))
is used.
Delete PopupForm has OnLoad js func used to animate the row that is about to be deleted, and the post action will delete the item and return the item's Id, the js func will use grid.api.select to select and remove the row, if there's no rows left grid.api.load will be called.
Create and Edit PopupForms are in the same Group (.Group("dinner")), this way when you open the edit view the create closes and the other way around. They are returning the same view (Create.cshtml) so opening both at the same time will give non unique ids for the Lookup/MultiLookup which will break them. Of course if you need to have both Edit and Create PopupForm open at the same time you can use .Prefix("prefix") on the helper to achieve unique ids.

Tip: make sure to use "return PartialView" for PopupForm/Popup views this will ignore _viewstart.cshtml so that you don't use the _Layout.cshtml and realod all the scripts, and as a result break the app.
GridCrudDemo/Index.cshtml
@Html.InitCrudPopupsForGrid("DinnersGrid", "DinnersGridCrud")

<div class="bar">
<div style="float: right;">
@Html.Awe().TextBox("txtSearch").Placeholder("search...").CssClass("searchtxt")
</div>
<button type="button" onclick="awe.open('createDinnersGrid')" class="awe-btn mbtn">Create</button>
</div>

@(Html.Awe().Grid("DinnersGrid")
.Mod(o => o.PageInfo().ColumnsSelector())
.Url(Url.Action("GridGetItems", "DinnersGridCrud"))
.Parent("txtSearch", "search")
.Height(350)
.Columns(
new Column { Bind = "Id", Width = 55 },
new Column { Bind = "Name" },
new Column { Bind = "Date" },
new Column { Bind = "Chef.FirstName,Chef.LastName", ClientFormat = ".ChefName", Header = "Chef" },
new Column { ClientFormat = ".Meals", Header = "Meals" },
new Column { ClientFormat = GridUtils.EditFormatForGrid("DinnersGrid"), Width = 50 }.Mod(o => o.Nohide()),
new Column { ClientFormat = GridUtils.DeleteFormatForGrid("DinnersGrid"), Width = 50 }.Mod(o => o.Nohide())))
Demos/Grid/DinnersGridCrudController.cs
/// <summary>
/// Note: If your Key Property is not "Id" (but "MyId"), you need to change the Key = "MyId" in GridGetItems and it in the view
/// change the Bind = "MyId" (if you're showing the id column),
/// and for the action columns you can either specify the MyId property (e.g. GridUtils.EditFormatForGrid("DinnersGrid", "MyId"));
/// or in MapToGridModel additionally to o.MyId add another property Id = o.MyId
/// parameters for Edit, Delete controller Actions need to remain called "id", that's how they are set in GridUtils.cs (params:{{ id: );
/// Edit and Delete post actions must return an object with property "Id" - in utils.js itemEdited and itemDeleted funcs expect it this way;
/// </summary>
public class DinnersGridCrudController : Controller
{
private static object MapToGridModel(Dinner o)
{
return
new
{
o.Id,
o.Name,
Date = o.Date.ToShortDateString(),
ChefName = o.Chef.FirstName + " " + o.Chef.LastName,
Meals = string.Join(", ", o.Meals.Select(m => m.Name))
};
}

public ActionResult GridGetItems(GridParams g, string search)
{
search = (search ?? "").ToLower();
var items = Db.Dinners.Where(o => o.Name.ToLower().Contains(search)).AsQueryable();

return Json(new GridModelBuilder<Dinner>(items, g)
{
Key = "Id", // needed for api select, update, tree, nesting, EF
GetItem = () => Db.Get<Dinner>(Convert.ToInt32(g.Key)), // called by the grid.api.update ( edit popupform success js func )
Map = MapToGridModel
}.Build());
}

public ActionResult Create()
{
return PartialView();
}

[HttpPost]
public ActionResult Create(DinnerInput input)
{
if (!ModelState.IsValid) return PartialView(input);

var dinner = Db.Insert(new Dinner
{
Name = input.Name,
Date = input.Date.Value,
Chef = Db.Get<Chef>(input.Chef),
Meals = input.Meals.Select(mid => Db.Get<Meal>(mid)),
BonusMeal = Db.Get<Meal>(input.BonusMealId)
});

return Json(MapToGridModel(dinner)); // returning grid model, used in grid.api.renderRow
}

public ActionResult Edit(int id)
{
var dinner = Db.Get<Dinner>(id);

var input = new DinnerInput
{
Id = dinner.Id,
Name = dinner.Name,
Chef = dinner.Chef.Id,
Date = dinner.Date,
Meals = dinner.Meals.Select(o => o.Id),
BonusMealId = dinner.BonusMeal.Id
};

return PartialView("Create", input);
}

[HttpPost]
public ActionResult Edit(DinnerInput input)
{
if (!ModelState.IsValid) return PartialView("Create", input);
var dinner = Db.Get<Dinner>(input.Id);

dinner.Name = input.Name;
dinner.Date = input.Date.Value;
dinner.Chef = Db.Get<Chef>(input.Chef);
dinner.Meals = input.Meals.Select(mid => Db.Get<Meal>(mid));
dinner.BonusMeal = Db.Get<Meal>(input.BonusMealId);
Db.Update(dinner);

// returning the key to call grid.api.update
return Json(new { Id = dinner.Id });
}

public ActionResult Delete(int id)
{
var dinner = Db.Get<Dinner>(id);

return PartialView(new DeleteConfirmInput
{
Id = id,
Message = string.Format("Are you sure you want to delete dinner <b>{0}</b> ?", dinner.Name)
});
}

[HttpPost]
public ActionResult Delete(DeleteConfirmInput input)
{
Db.Delete<Dinner>(input.Id);
return Json(new { Id = input.Id });
}
}
DinnersGridCrud/create.cshtml
@model AwesomeMvcDemo.ViewModels.Input.DinnerInput
@using (Html.BeginForm())
{
using (Html.Awe().BeginContext())
{
@Html.EditorFor(o => o.Name)
@Html.EditorFor(o => o.Date)
@Html.EditorFor(o => o.Chef)
@Html.EditorFor(o => o.Meals)
@Html.EditorFor(o => o.BonusMealId)
}
}
Helpers/Awesome/CrudHelpers.cs

public static IHtmlString InitCrudPopupsForGrid<T>(this HtmlHelper<T> html, string gridId, string crudController, int createPopupHeight = 430)
{
var url = GetUrlHelper(html);

var result =
html.Awe()
.InitPopupForm()
.Name("create" + gridId)
.Group(gridId)
.Height(createPopupHeight)
.Url(url.Action("Create", crudController))
.Title("Create item")
.Modal()
.Success("utils.itemCreated('" + gridId + "')")
.ToString()

+ html.Awe()
.InitPopupForm()
.Name("edit" + gridId)
.Group(gridId)
.Height(createPopupHeight)
.Url(url.Action("Edit", crudController))
.Title("Edit item")
.Modal()
.Success("utils.itemEdited('" + gridId + "')")

+ html.Awe()
.InitPopupForm()
.Name("delete" + gridId)
.Group(gridId)
.Url(url.Action("Delete", crudController))
.Success("utils.itemDeleted('" + gridId + "')")
.OnLoad("utils.delConfirmLoad('" + gridId + "')") // calls grid.api.select and animates the row
.Height(200)
.Modal();

return new MvcHtmlString(result);
}
Utils/GridUtils.cs
namespace AwesomeMvcDemo.Utils
{
public static class GridUtils
{
public static string EditFormat(string popupName, string key = "Id")
{
return string.Format("<button type='button' class='awe-btn' onclick=\"awe.open('{0}', {{ params:{{ id: '.{1}' }} }})\"><span class='ico-edit'></span></button>",
popupName, key);
}

public static string DeleteFormat(string popupName, string key = "Id", string deleteContent = "<span class='ico-del'></span>", string btnClass = null)
{
return string.Format("<button type='button' class='awe-btn {3}' onclick=\"awe.open('{0}', {{ params:{{ id: '.{1}' }} }})\">{2}</button>",
popupName, key, deleteContent, btnClass);

// if you need to set title, buttons dynamically you can do it like this:
//awe.open('{0}', {{ params:{{ id: '.{1}' }}, udb:0, p: {{ t:'my title' }}, b:['btn1', btn1Func] }})
}

public static string InlineDeleteFormat(string popupName, string key = "Id")
{
return DeleteFormat(popupName, key, btnClass:"inlDel") + "<button type='button' class='awe-btn gcancelbtn' style='display:none;'>Cancel</button>";
}

public static string InlineEditFormat()
{
return "<button type='button' class='awe-btn geditbtn'>Edit</button><button type='button' class='awe-btn gsavebtn' style='display:none;'>Save</button>";
}

public static string EditFormatForGrid(string gridId, string key = "Id")
{
return EditFormat("edit" + gridId, key);
}

public static string DeleteFormatForGrid(string gridId, string key = "Id")
{
return DeleteFormat("delete" + gridId, key);
}

public static string EditGridNestFormat()
{
return "<button type='button' class='awe-btn editnst'><span class='ico-edit'></span></button>";
}

public static string DeleteGridNestFormat()
{
return "<button type='button' class='awe-btn delnst'><span class='ico-del'></span></button>";
}

public static string AddChildFormat()
{
return "<button type='button' class='awe-btn' onclick=\"awe.open('createNode', { params:{ parentId: '.Id' } })\">add child</button>";
}
}
}