How to call a static method in Kendo Grid column - asp.net-mvc

I use a Kendo grid to show my table fields like this:
#(Html.Kendo().Grid<MyProject.Admin.Models.MyViewModel>(Model)
.Name("id")
.Columns(columns =>
{
columns.Bound(c => c.ID).Filterable(false);
columns.Bound(c => c.ModelNo).Filterable(false);
It works fine but one of the fields is userId , a GUID field and I want to call a static method which returns Username. I've already created this method. The method is
public static string GetUserName(Guid UserId)
{
var db = new ApplicationDbContext();
var user = (from k in db.Users where k.Id == UserId.ToString() select k).FirstOrDefault();
if(user != null)
{
return user.UserName;
}
else
{
return "-";
}
}
So what I need is to call this method in Kendo Grid, something like:
columns.Bound(c => c.UserID).Template(#<text>
<strong>#Tools.GetUserName(c.UserID)</strong>
</text>);

columns.Bound(p => p.Title).Template(#<text>
<strong>#item.Title</strong>
</text>);
simply generates javascript like this one
columns: [{
...
template: "<strong>#:Title#</strong>"
}],
And template: "<text><strong>#:Title#</strong></text>" further processed by templating engine in the Kendo UI Framework at client side. Therefore replacing #:Title# to any C# function wouldn't be recognized at browser end.

Related

kendo mvc editor not binding to selected dropdown property

Using inline editing from a kendo grid (v 2017.3.913), the editor template used for the dropdown is not using the property id to set the selected value in the list (or it's another issue but related).
I tried several solutions from like-kind SO questions but nothings has yielded the expected results.
kendo grid
//ParentOrganization is the target property
#(Html.Kendo().Grid<OrganizationGridViewModel>()
.Name("organizationGrid")
.Columns(columns =>
{
columns.Bound(o => o.Id).Width(150).Hidden(true);
columns.Bound(o => o.Name);
columns.Bound(o => o.ParentOrganization).ClientTemplate("#= (ParentOrganization.Id == 0) ? ' ' : ParentOrganization.Name #").EditorTemplateName("ParentOrganization");
columns.Bound(o => o.OrganizationTypeDescription).Width(165);
columns.Command(command =>
{
command.Edit().Text(" ").HtmlAttributes(new { title = "Edit Organization" });
command.Destroy().Text(" ").HtmlAttributes(new { title = "Delete Organization" });
}).Width(250);
})
.ToolBar(toolbar => toolbar.Create().Text("New"))
.Editable(editable => editable.Mode(GridEditMode.InLine).ConfirmDelete("Are you sure you want to delete this organization?")
.DisplayDeleteConfirmation("Organization deleted"))
...
Since the bound column is an navigational object (versus a primitive type) I use the [UIHint] in the viewmodel to point to an editor template, so that the object is mapped properly.
viewmodel used in the grid
public class OrganizationGridViewModel
{
...
// NOTE: the Organization object has "Id" and "Name" properties
[UIHint("ParentOrganization")]
public Organization ParentOrganization { get; set; }
}
editor template
#(Html.Kendo().DropDownList()
.Name("ParentOrganization")
.DataTextField("Text")
.DataValueField("Value")
.BindTo((IEnumerable) ViewData["OrganizationSelectList"])
)
And finally, the data used by the dropdownlist:
var orgSelectList = organizations.Select(n => new SelectListItem
{
Text = n.Name,
Value = n.Id.ToString()
}).ToList();
ViewData["OrganizationSelectList"] = new SelectList(orgSelectList, "Value", "Text");
NOTE
I also tried creating a SelectList using "Id" & "Name" (propagated the change to the editor as well - replaced "Value" & "Text") so it would align with the ParentOrganization object but that ended up producing "undefined" list items.
orgSelectItems.AddRange(organizations.Select( n => new BaseSelectItem
{
Id = n.Id,
Name = n.Name
}));
ViewData["OrganizationSelectList"] = new SelectList(orgSelectList, "Id", "Name");
This is how im getting data into and out of my dropdowns for Kendo
#(Html.Kendo().DropDownList()
.Name("showProcessed")
.DataTextField("OptionText")
.DataValueField("ViewOption")
.AutoBind(true)
.SelectedIndex(2)
.Events(e => e.Change("fe_DiaryItem.processedChange"))
.HtmlAttributes(new { style = "width: 250px;" })
.DataSource(ds =>
{
ds.Read("DiaryGridViewOptions", "ControllerName");
})
)
In this instance I populate the object with the DataSource, and select the index using .SelectedIndex(x).
I have other examples of how to set the index if you need but this is working production code.
----Edit----
#{
var idxDst = 0;
if (Model.DiaryTimeSlot != null && Model.DiaryTimeSlotSelectedId > 0)
{
idxDst = Model.DiaryTimeSlot.IndexOf(Model.DiaryTimeSlot.First(x => x.DiaryTimeSlotID == Model.DiaryTimeSlotSelectedId));
}
}
#(Html.Kendo().DropDownList()
.Name("DiaryTimeSlot")
.DataTextField("Description")
.DataValueField("DiaryTimeSlotID")
.SelectedIndex(idxDst)
.BindTo(Model.DiaryTimeSlot)
.DataSource(ds =>
{
ds.Read("DiaryTimeSlotOptions", "ControllerName");
})
)
It appears that [Kendo or MVC helpers themselves] don't like you using "proper" [Domain] objects - appears to confuse the binding. I believe the root cause is the property names are the same (Id & Name) and need to be different. I was using a domain object Organization as the property's type. I created another viewmodel to represent the organization and used different property names:
new viewmodel to represent the org
instead of using "Id" & "Name" as the mapped text and value properties I'm using the following "ParentOrganization-x" properties:
public class ParentOrganizationViewModel
{
public int? ParentOrganizationId { get; set; }
public string ParentOrganizationName { get; set; }
}
So an update to the grid viewmodel will reflect the new org viewmodel:
public class OrganizationGridViewModel
{
...
[UIHint("ParentOrganization")]
public ParentOrganizationViewModel ParentOrganization { get; set; }
}
Also, instead of returning a SelectList as the datasource to the dropdown, it's a straight viewlmodel list:
var orgSelectList = organizations.Select(n => new ParentOrganizationViewModel()
{
ParentOrganizationName = n.Name,
ParentOrganizationId = n.Id
}).ToList();
ViewData["OrganizationSelectList"] = orgSelectList;
The final changes are in the editor template, to change the DataTextField and DataValueField properties match the org viewmodel:
#(Html.Kendo().DropDownList()
.Name("ParentOrganization")
.DataTextField("ParentOrganizationName")
.DataValueField("ParentOrganizationId")
.AutoBind(true)
.ValuePrimitive(true)
.BindTo((IEnumerable) ViewData["OrganizationSelectList"])
)

Kendo Grid: Foreign Key Dropdown does not update grid cell after update

I have a Kendo MVC grid that contains a nullable property (short) that is bound as a foreign key and uses a dropdown list as an editor template. I am also using inline editing.
When the property value is null, the dropdown list selected value does not get set into the grid cell after the update button is clicked. This works fine if incell editing is used. I am looking for a workaround that will solve my problem. I am including a stripped down version of my code below
Everything works if the nullable value is set to a non-null value.
GRID
#(Html.Kendo().Grid<AssetViewModel>()
.Name("DealAssets")
.Columns(c =>
{
c.Bound(x => x.Name);
c.ForeignKey(x => x.AssetTypeID, (IEnumerable<SelectListItem>)ViewBag.AssetTypeList, "Value", "Text");
c.ForeignKey(x => x.SeniorityTypeID, seniorityTypeList, "Value", "Text").EditorTemplateName("GridNullableForeignKey");
c.ForeignKey(x => x.RateBaseID, rateBaseList, "Value", "Text").EditorTemplateName("GridNullableForeignKey"); ;
c.Command(m => { m.Edit(); m.Destroy(); });
})
.ToolBar(toolbar => toolbar.Create().Text("Add New Asset"))
.Editable(x => x.Mode(GridEditMode.InLine))
.DataSource(ds => ds
.Ajax()
.Model(model => model.Id(request => request.ID))
.Read(read => read.Action("ReadAssets", "Deal", new { id = Model.ID }))
.Create(create => create.Action("CreateAsset", "Deal", new { currentDealID = Model.ID }))
.Update(update => update.Action("UpdateAsset", "Deal"))
.Destroy(destroy => destroy.Action("DeleteAsset", "Deal"))
)
)
EDITOR TEMPLATE
#model short?
#{
var controlName = ViewData.TemplateInfo.GetFullHtmlFieldName("");
}
#(
Html.Kendo().DropDownListFor(m => m)
.Name(controlName)
.OptionLabel("- Please select -")
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
)
UPDATE ACTION
public ActionResult UpdateAsset([DataSourceRequest] DataSourceRequest request, int ID)
{
var dealAsset = DataContext.DealAssets.SingleOrDefault(o => o.ID == ID);
if (dealAsset != null)
{
if (TryUpdateModel(dealAsset.Asset, new[] {"Name","AssetTypeID","SeniorityTypeID","RateBaseID" }))
{
DataContext.SaveChanges();
}
}
return Json(new[] { new AssetViewModel(dealAsset) }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
}
Telerik just recently added a new HTML attribute, data_value_primitive, to their selectlist that addresses the issue above. The new attribute should be added in the foreign key editor template and set to true.
Html.Kendo().DropDownListFor(m => m)
.Name(controlName)
.OptionLabel("- Please select -")
.BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
**.HtmlAttributes(new { data_value_primitive = true})**
This last section is a modification to the update method to account for the grid not passing back null properties when doing the ajax call. I think this has more to do with how the TryUpdateModel method works
...
if (TryUpdateModel(dealAsset.Asset, new[] {"Name","AssetTypeID","SeniorityTypeID","RateBaseID" }))
{
// If no property passed back then set it to null
var senorityTypeID = ValueProvider.GetValue("SeniorityTypeID");
if (senorityTypeID == null)
{
dealAsset.Asset.SeniorityTypeID = null;
} else {
dealAsset.Asset.SeniorityTypeID = (short)senorityTypeID.ConvertTo(typeof(short));
}
var rateBaseID = ValueProvider.GetValue("RateBaseID");
if (rateBaseID == null)
{
dealAsset.Asset.RateBaseID = null;
} else {
dealAsset.Asset.RateBaseID = (byte)rateBaseID.ConvertTo(typeof(byte));
}
DataContext.SaveChanges();
}
'''

KendoUI Grid Ajax Binding Parameters For Select

I have a basic KendoUI Grid for my ASP.NET MVC app which uses ajax binding for the read. I'd like to enhance this so that a Form above the grid is used to help select data that should be displayed in the grid. This is a standard search form with basic fields like First Name, Last Name, Date of Birth, Customer Source, etc. with a search button. When the search button is pressed, I want to force the grid to go get the data that meets the criteria from the controller by passing in the Search Model with the fields I referenced above.
The search form is contained within the _CustomerSearch partial view.
I've implemented this sort of thing before with the Telerik MVC extensions by tapping into the OnDataBinding client event and updating the parameter values there and then manually making the Ajax call to get the data. It doesn't appear KendoUI will operate this same way.
View
#Html.Partial("_CustomerSearch", Model)
<hr>
#(Html.Kendo().Grid<ViewModels.CustomerModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.Id).Hidden(true);
columns.Bound(p => p.FirstName);
columns.Bound(p => p.LastName);
columns.Bound(p => p.DateOfBirth).Format("{0:MM/dd/yyyy}");
columns.Bound(p => p.IsActive);
})
.Scrollable()
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("_Search", "Customer"))
)
)
Controller
public ActionResult _Search([DataSourceRequest]DataSourceRequest request)
{
return Json(DataService.GetCustomers2().ToDataSourceResult(request));
}
I envision the controller looking something like this, but can't find any examples of anything being implemented this way, which is what I need help with.
public ActionResult _Search([DataSourceRequest]DataSourceRequest request, CustomerSearchModel customerSearchModel)
{
return Json(DataService.GetCustomers2(customerSearchModel)
.ToDataSourceResult(request));
}
Nicholas answer could work if your requirements can be solved with the built in filtering. But if your requirements can be solved with the built filtering why do you want to create a custom search form?
So I suppose you have a reason to do the search manually so here is how we've done it in our project (so maybe there is more easier way but still this worked for us):
The controller action is fine:
public ActionResult _Search([DataSourceRequest]DataSourceRequest request,
CustomerSearchModel customerSearchModel)
{
return Json(DataService.GetCustomers2(customerSearchModel)
.ToDataSourceResult(request));
}
Next step: you need a JavaScript function which collects the data from the search form (the property names of the JS object should match the property names of your CustomerSearchModel) :
function getAdditionalData() {
// Reserved property names
// used by DataSourceRequest: sort, page, pageSize, group, filter
return {
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
//...
};
}
Then you can configure this function to be called on each read:
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("_Search", "Customer")
.Data("getAdditionalData"))
)
Finally in your button click you just need to refresh the grid with:
$('#Grid').data('kendoGrid').dataSource.fetch();
You can set the filters on the grid by calling filter on the grid's data source.
So in your button's onclick handler function, put something like this:
var $Grid = $('#Grid').data('kendoGrid');
$Grid.dataSource.filter([
{ field: 'FirstName', operator: 'eq', value: $('#firstName').val() },
{ field: 'LastName', operator: 'eq', value: $('#lastName').val() }
]);
Here's a link to the Kendo docs: DataSource.filter
Refer Pass Additional Data to the Action Method
To pass additional parameters to the action use the Data method. Provide the name of a JavaScript function which will return a JavaScript object with the additional data:
A working Search example listed below:
Important: type="button" for the button; And AutoBind(false) for Grid; otherwise, it won’t work
VIEW
#model IEnumerable<KendoUIMvcSample.Models.Sample>
#{
ViewBag.Title = "Index";
}
<script type="text/javascript">
function getAdditionalData()
{
return {
FirstName: 'A',
LastName: 'B',
};
}
$(document).ready(function ()
{
$('#Submit1').click(function ()
{
alert('Button Clicked');
//Refresh the grid
$('#ssgrid222').data('kendoGrid').dataSource.fetch();
});
});
</script>
<h2>Index</h2>
#using (Html.BeginForm())
{
#(Html.Kendo().Grid<KendoUIMvcSample.Models.Sample>()
.Name("ssgrid222")
.Columns(columns => {
columns.Bound(p => p.SampleDescription).Filterable(false).Width(100);
columns.Bound(p => p.SampleCode).Filterable(false).Width(100);
columns.Bound(p => p.SampleItems).Filterable(false).Width(100);
})
.AutoBind(false)
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "Sample")
.Data("getAdditionalData"))
)
)
<input id="Submit1" type="button" value="SubmitValue" />
}
Controller
namespace KendoUIMvcSample.Controllers
{
public class SampleController : Controller
{
public ActionResult Index()
{
SampleModel AddSample = new SampleModel();
Sample s1 = new Sample();
return View(GetSamples());
}
public static IEnumerable<Sample> GetSamples()
{
List<Sample> sampleAdd = new List<Sample>();
Sample s12 = new Sample();
s12.SampleCode = "123se";
s12.SampleDescription = "GOOD";
s12.SampleItems = "newone";
Sample s2 = new Sample();
s2.SampleCode = "234se";
s2.SampleDescription = "Average";
s2.SampleItems = "oldone";
sampleAdd.Add(s12);
sampleAdd.Add(s2);
return sampleAdd;
}
public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request, CustomerSearchModel customerSearchModel)
{
string firstParam = customerSearchModel.FirstName;
return Json(GetOrders().ToDataSourceResult(request));
}
private static IEnumerable<Sample> GetOrders()
{
return GetSamples();
}
}
public class CustomerSearchModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Model
namespace KendoUIMvcSample.Models
{
public class SampleModel
{
public List<Sample> samples;
}
public class Sample
{
public string SampleDescription { get; set; }
public string SampleCode { get; set; }
public string SampleItems { get; set; }
}
}

Telerik Grid databinding to call HttpPost method

I am working on ASP.NET MVC and I have a View on which form data is retrieved in the HttpPost action. It works fine when the HttpPost action is called. I use the form data to query a database and the result from the database is bound to a TELERIK Grid control. It displays data fine, but paging is not working.
The issue is that when I try to switch to another page, it calls the HTTPGET action method and not the HttpPost action method and hence no data is retrieved from the database.
Any help is appreciated.
Here is the code for the View and Controller:
//-------------View------------------------------------
#(Html.Telerik().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.DealerName);
columns.Bound(o => o.DealerNumber);
columns.Bound(o => o.ServiceDealerNumber);
columns.Bound(o => o.CMDealerNumber);
columns.Bound(o => o.PurchaseDealerNumber);
columns.Bound(o => o.Address);
columns.Bound(o => o.City);
columns.Bound(o => o.State);
columns.Bound(o => o.Zip);
})
.DataBinding(dataBinding =>
{
dataBinding.Server().Select("DealerProfile", "DealerManagement", new { testVal = "test" }).Enabled(true);
dataBinding.Ajax().Select("DealerProfile", "DealerManagement", new { testVal = "test" } ).Enabled(true);
})
.Scrollable(scrolling => scrolling.Enabled(true))
.Sortable(sorting => sorting.Enabled(true))
.Pageable(paging =>
paging.PageSize(20)
.Style(GridPagerStyles.NextPreviousAndNumeric)
.Position(GridPagerPosition.Bottom)
)
.Filterable(filtering => filtering.Enabled(true))
.Groupable(grouping => grouping.Enabled(true))
.Footer(true)
)
//---------------Controller Actions---------------------------------------
//
// GET: /DealerManagement/DealerProfile/
public ActionResult DealerProfile()
{
return View();
}
//
// POST: /DealerManagement/DealerProfile/
[HttpPost]
public ActionResult DealerProfile(FormCollection formValues)
{
string dealerNumber = Request.Form["DealerNumber"];
string dealerName = Request.Form["DealerName"];
DealerProfilesViewModel dealerProfilesViewModel = new DealerProfilesViewModel();
dealerProfilesViewModel.DealerProfiles = new List<DealerProfileViewModel>();
if (!dealerNumber.Trim().Equals(string.Empty))
{
DealerInfoCollection dealers = _iDealerProfileService.GetDealerInfoFromDealerNumber(dealerNumber);
foreach (var item in dealers)
{
DealerProfileViewModel dealerProfileViewModel = new DealerProfileViewModel();
dealerProfileViewModel.DealerName = item.Dealer_Name;
dealerProfileViewModel.DealerNumber = item.Dealer_No;
dealerProfileViewModel.ServiceDealerNumber = item.Service_Dealer_No;
dealerProfileViewModel.CMDealerNumber = item.CM_Dealer_No;
dealerProfileViewModel.PurchaseDealerNumber = item.PUR_Dealer_No;
dealerProfileViewModel.Address = item.Address;
dealerProfileViewModel.City = item.City;
dealerProfileViewModel.State = item.State;
dealerProfileViewModel.Zip = item.Zip;
dealerProfilesViewModel.DealerProfiles.Add(dealerProfileViewModel);
}
}
else if (!dealerName.Trim().Equals(string.Empty))
{
DealerInfoCollection dealers = _iDealerProfileService.GetDealerInfoFromDealerName(dealerName);
foreach (var item in dealers)
{
DealerProfileViewModel dealerProfileViewModel = new DealerProfileViewModel();
dealerProfileViewModel.DealerName = item.Dealer_Name;
dealerProfileViewModel.DealerNumber = item.Dealer_No;
dealerProfileViewModel.ServiceDealerNumber = item.Service_Dealer_No;
dealerProfileViewModel.CMDealerNumber = item.CM_Dealer_No;
dealerProfileViewModel.PurchaseDealerNumber = item.PUR_Dealer_No;
dealerProfileViewModel.Address = item.Address;
dealerProfileViewModel.City = item.City;
dealerProfileViewModel.State = item.State;
dealerProfileViewModel.Zip = item.Zip;
dealerProfilesViewModel.DealerProfiles.Add(dealerProfileViewModel);
}
}
if (!String.IsNullOrEmpty(dealerName) && !String.IsNullOrEmpty(dealerNumber))
{
dealerProfilesViewModel = null;
}
return View(dealerProfilesViewModel.DealerProfiles);
}
First your controller method needs the GridAction attribute. Second it must use the GridModel type as a model. This is required for ajax binding. You can check the ajax binding help article as well as the ajax binding online demo which show what the required steps are. Most probably you should define a separate action method just for the ajax binding.
Lastly it seems that the JavaScript of the grid does not kick in - the fact that it is making HTTP GET requests indicate that. Check that there is a ScriptRegistrar component declared AFTER the grid.

Telerik MVC Grid Edit Template DropDownList problem

I am getting a null value passed to my ajax .Update("_SaveAjaxEditing", "AptProfile") in my controller when using the dropdownlist client Edit Template.
property in my FormViewModel that my grid is bound to:
[UIHint("BuildingsGrid"), Required]
[DisplayName("Building ID")]
public int BuildingID
{
get;
set;
}).
Here is my view:
<%= Html.Telerik().Grid<PayRent.Models.AptProfileFormViewModel1>()
.Name("Profiles")
.DataKeys(dataKeys => dataKeys.Add(c => c.AptProfileID))
.ToolBar(commands => commands.Insert())
.DataBinding(binding =>
{
binding.Ajax()
.Select("GetProfiles", "AptProfile")
.Insert("_InsertAjaxEditing", "AptProfile")
.Update("_SaveAjaxEditing", "AptProfile")
.Delete("_DeleteAjaxEditing", "AptProfile");
})
.Columns(columns =>
{
columns.Bound(o => o.AptProfileID);
columns.Bound(o => o.BuildingID);
columns.Bound(o => o.AptID);
columns.Bound(o => o.AptRate);
columns.Bound(o => o.AptSize);
columns.Bound(o => o.MoveInDate);
columns.Command(s =>
{
s.Edit();
s.Delete();
});
})
.Editable(editing => editing.Mode(GridEditMode.InLine))
.ClientEvents(events => events.OnEdit("onEdit"))
.Pageable()
%>
</p>
<script type="text/javascript">
function onEdit(e) {
// $(e.form).find('#BuildingsGrid').data('tDropDownList').select(function (dataItem) {
// return dataItem.Text == e.dataItem['BuildingGrid'];
// });
}
</script>
My EditTemplate:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.Telerik().DropDownList()
.Name("BuildingsGrid")
.BindTo(new SelectList((IEnumerable)ViewData["Buildings"], "BuildingID", "Name"))
%>)
Here is my Controller:
[AcceptVerbs(HttpVerbs.Post)]
//[CultureAwareAction]
[GridAction]
public ActionResult _SaveAjaxEditing(int id, int? BuildingGrid)
{
ApartmentProfileRepository repo = new ApartmentProfileRepository();
AptProfile profile = repo.Get(id);
TryUpdateModel(profile);
repo.Save();
return View(new GridModel(GetAllProfiles()));
}
If you want to keep everything Ajax-ified, you have do it without using the viewbag. My combobox is in a separate editor template. All you have to do is return the SelectList as a JsonResult. That said, I only recommended doing it that way if you expect the data in that combobox to change while the user is on the page, because it calls the server method every time the combo is opened.
In my example below, because the user can add a Category on the same page as they're selecting a Category, I need it to hit the server each time. But on other pages, I use server-side binding (via the ViewBag/ViewData) so that it only hits the server once.
My editor template:
#(Html.Telerik().ComboBox()
.Name("YourNameGoesHere")
.DataBinding(binding => binding.Ajax().Select("SelectCategoriesForComboBox","Shared")))
Then in the controller:
public EquipmentEntities db = new EquipmentEntities();
public List<SelectListItem> CategoryList
{
get
{
var m = db.Categories
.Select(e => new{ Id = e.Id, Name = e.Name })
.OrderBy(e => e.name);
List<SelectListItem> sl = new SelectListItem(m.ToList(), "Id", "Name").ToList();
//insert a blank item as the first entry
sl.Insert(0, (new SelectListItem { Text = "", Value = string.Empty }));
return sl;
}
}
[HttpPost]
public ActionResult SelectCategoryForComboBox()
{
return new JsonResult { Data = CategoryList };
}
Maybe I'm a little bit late, but hopefully it helps someone out.
First, you need to match up the name of your column in the view with the name of your edit template and controller action parameter. I don't think the int parameter needs to be nullable in the controller action.
Then in your controller action you need to set the ViewData["Buildings"] for the edit template; then select the current value in your profile object before returning the view.
e.g.
public ActionResult _SaveAjaxEditing(int id, int BuildingsGrid)
{
ApartmentProfileRepository repo = new ApartmentProfileRepository();
AptProfile profile = repo.Get(id);
// Save the building ID in the profile
profile.BuildingID = BuildingsGrid;
TryUpdateModel(profile);
repo.Save();
// Load the Building objects into the ViewData
ViewData["Buildings"] = GetBuildings();
return View(new GridModel(GetAllProfiles()));
}

Resources