Telerik MVC Grid Master Detail Cascading Dropdowns - asp.net-mvc

I am using a master-detail Telerik MVC Grid on two levels.
The first level contains a drop-down of Customers and some misc data.
The second level contains a drop-down of Cars that are linked to the customer on the first level and some misc data.
I am now using a foreign key column to show the dropdowns of cars and clients.
How can the second dropdown be filtered by the customer on the first level?
Code:
#(Html.Telerik().Grid<Models.ClientsModel>()
.Name("Grid")
.ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
.DataKeys(keys => keys.Add(c => c.ClientLineID))
.Columns(columns =>
{
columns.ForeignKey(o => o.ClientID, (System.Collections.IEnumerable)ViewBag.Client, "ClientID", "Name")
.Width(330)
.Title("Client");
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.ImageAndText);
commands.Delete().ButtonType(GridButtonType.ImageAndText);
}).Width(250);
})
.DetailView(car => car.ClientTemplate(
Html.Telerik().Grid<Delta.Models.CarModel>()
.Name("Car_<#= ClientID #>")
.DataKeys(keys => keys.Add(c => c.LineID))
.ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_CarLineIndex", "Client", new { id = "<#= ClientID #>" })
.Insert("_CarLineCreate", "Client", new { id = "<#= ClientID #>" })
.Update("_CarLineUpdate", "Client")
.Delete("_CarLineDelete", "Client");
})
.Columns(columns =>
{
columns.ForeignKey(o => o.CarID, (System.Collections.IEnumerable)ViewBag.Cars,
"CarID", "No")
.Width(500)
.Title("Car");
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.ImageAndText);
commands.Delete().ButtonType(GridButtonType.ImageAndText);
}).Width(200);
})
.Editable(editing => editing => editing.Mode(GridEditMode.InLine))
.Scrollable(c => c.Height("auto"))
.Resizable(resizing => resizing.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.KeyboardNavigation()
.Footer(false)
.ToHtmlString()
))
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_ClientIndex", "Client")
.Insert("_ClientCreate", "Client")
.Update("_ClientUpdate", "Client")
.Delete("_ClientDelete", "Client");
})
.Scrollable(c => c.Height("auto"))
.Editable(editing => editing.Mode(GridEditMode.InLine))
.Pageable(o => o.PageSize(50))
.Filterable()
.KeyboardNavigation()
.Groupable())
I am thinking that the code might involve some javascript on the OnDetailViewExpand event, but I can't figure out what.
The only solution I have now is to split the grid into separate views and build cascasing comboboxes there.

Unfortunately I cannot comment on posts yet to clarify some facts about your question. I'll make some assumptions in my answer so that we can work out the exact nature of the problem. You have two model classes one for each grid ClientsModel and CarModel. You are filtering the CarModel (second)grid with fields from the ClientsModel (first)grid.
You are not restricted to just one(<= ClientID =>) parameter in your select binding. You can use other fields from the ClientsModel class the same way as ClientID.
Sample Code:
dataBinding.Ajax().Select("_CarLineIndex", "Client", new { id = "<#= ClientID #>", city = "<#= City #>" })
Here is a working example with mock data that illustrates the method mentioned above:
Client Class
public class Client
{
public int ClientId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
Car Class
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string Color { get; set; }
}
HomeController
[GridAction]
public ActionResult _Index()
{
Client c1 = new Client() { ClientId = 1, City = "Boston", FirstName = "Ted", LastName = "Boder" };
Client c2 = new Client() { ClientId = 2, City = "New York", FirstName = "Chris", LastName = "Tobb" };
Client[] clients = {c1, c2};
return View(new GridModel(clients));
}
[GridAction]
public ActionResult _Cars(int ClientId, string City)
{
Car c1 = new Car() { Color = "Yellow", Make = "Ford", Model = "Mustang", Year = 2012 };
Car c2 = new Car() { Color = "Black", Make = "Toyota", Model = "Camry", Year = 2010 };
Car[] cars = { c1, c2 };
return View(new GridModel(cars));
}
View
#(Html.Telerik().Grid<Client>()
.Name("Clients")
.Columns(columns =>
{
columns.Bound(o => o.FirstName);
columns.Bound(o => o.LastName);
columns.Bound(o => o.City);
})
.DetailView(clientDetailView => clientDetailView.ClientTemplate(
Html.Telerik().Grid<Car>()
.Name("ClientDetails_<#= ClientId #>")
.Columns(columns =>
{
columns.Bound(c => c.Make);
columns.Bound(c => c.Model);
columns.Bound(c => c.Year);
columns.Bound(c => c.Color);
})
.DataBinding(db2 => db2.Ajax().Select("_Cars", "Home", new { ClientID = "<#= ClientId #>", City = "<#= City #>" }))
.Pageable()
.Sortable()
.ToHtmlString()
))
.DataBinding(db1 => db1.Ajax().Select("_Index", "Home"))
.Pageable()
.Sortable()
.Filterable()
)
As you can see from the example I'm also passing a City parameter as well as a ClientId when binding the grid.
Let me know if I missed something.

You are correct that you will need to do this with javascript, and it is a matter of being able to filter cars by customers. Telerik allows you to add additional parameters using the "e.data" argument for most of their controls. So for example if you wanted to filter a city list based on a select state the CSHTML would look like this:
<td valign="top">
#(Html.Telerik().DropDownListFor(m => m.State)
.Name("State")
.ClientEvents(events => events.OnChange("State_Change"))
.BindTo(new SelectList(Model.GetStates()))
.HtmlAttributes(new { style = string.Format("width:{0}px", 160) })
)
</td>
<td valign="top">
#(Html.Telerik().AutoCompleteFor(m => m.City)
.Name("City")
.Encode(false)
.ClientEvents(events => {
events.OnDataBinding("City_AutoComplete");
})
.DataBinding(a => a.Ajax().Select("CityList", "Location"))
.AutoFill(true)
.HighlightFirstMatch(true)
.HtmlAttributes(new { style = string.Format("height: 17px; width:{0}px", 250) })
)
</td>
The javascript would look like this:
function City_AutoComplete(e) {
//pass state as an additional parameter here to filter
//this would be your customer for cars list
e.data = $.extend({}, e.data, { state: $("#State").val() });
}
function State_Change(e) {
//reset when the parent list selection changes
$('#City').data('tAutoComplete').text('');
$('#City').data('tAutoComplete').value('');
}

Nothing to complex, create client event onEdit, you can found sample on telerik demo, than after once created client write down dropedown selection change event code that will filter data for you car dropdown. to do this I would suggest you to call ajax and insert HTml for dropdown. If you have still doubt than let me know I will explain it in detail.
If you you really find this answer best or appropriate please vote it.. it will help...

Related

Kendo grid does not update data with custom dropdown

I'm trying to use a Kendo grid with inline editing but my data does not change on pressing update. Other columns have no problem, but the drop down data is not updated.
My model class is:
public class Validation
{
public string ParentParameterName { get; set; }
public string ParameterName { get; set; }
public string ParameterTitle { get; set; }
[UIHint("DataTypeList")]
public string DataType { get; set; }
[UIHint("EvetHyir")]
public string Required { get; set; }
public List<Validation> Value { get; set; }
}
My grid is:
#(Html.Kendo().Grid<Validation>()
.Name("keyJsonGrid")
.Columns(columns =>
{
columns.Bound(model => model.ParentParameterName).Title("Ana parametre ünvanı");
columns.Bound(model => model.ParameterTitle).Title("Parametre ünvanı");
columns.Bound(model => model.ParameterName).Title("Parametre Adı");
//columns.Bound(foo => foo.DataType).Title("TİP").EditorTemplateName("DataType").Sortable(false);
columns.Bound(p => p.DataType).Sortable(false).Width(180).EditorTemplateName("DataTypeList");
columns.Command(command => { command.Edit().Text("Düzenle"); command.Destroy().Text("Sil"); }).Width(250);
})
.Resizable(builder => builder.Columns(true))
.ToolBar(toolbar => toolbar.Create().Text("Yeni Ekle"))
.Editable(editable => editable
.Mode(GridEditMode.InLine)
.ConfirmDelete("Silinmesine emin misiniz?")
.DisplayDeleteConfirmation("Silinmesine emin misiniz?")
)
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] { 10, 25, 50, 75, 100 })
)
.Sortable(x => x.SortMode(GridSortMode.MultipleColumn))
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetJsonKeyList", "Key", new { KeyId = Model }))
.PageSize(25)
)
)
My dropdown is populated from an enum:
#(Html.Kendo().DropDownList()
// The name of the widget has to be the same as the name of the property.
.Name("DataType")
// The value of the drop-down is taken from the EmployeeID property.
.DataValueField("Text")
.DataTextField("Text")
.AutoBind(true)
// The text of the items is taken from the EmployeeName property.
.ValuePrimitive(true)
// A list of all employees which is populated in the controller.
.BindTo((System.Collections.IEnumerable)ViewData["DataTypes"])
)
Dropdown data population code:
KeyJsonDTO.DataType x = KeyJsonDTO.DataType.Integer;
ViewData["DataTypes"] = EnumToSelectList(x.GetType());
static List<SelectListItem> EnumToSelectList(Type enumType)
{
return Enum.GetValues(enumType)
.Cast<int>()
.Select(i => new SelectListItem
{
Value = i.ToString(),
Text = Enum.GetName(enumType, i),
})
.ToList();
}
When I press the "Edit" button, the dropdown does not show correct data, and when I press update data, it does not update.
I doubt you are actually using the dropdown you created. "DataType" is not the name of the field. It is the name of the editor template you save in the file system. You can use controls on page but as far as i know, only if it's a javascript grid. You need to make an editor template in the appropriate folder and change the definition of the control to be an dropdownfor(m => m). Then you don't have to name it.

Kendo ui MVC Grid Popup Editor Template DropDownListFor not working

I am using Kendo UI for ASP.MVC with Razor view and in Grid editing popup mode, EditorTemplate does not display value from Grid in DropDownListFor. What am I missing?
View:
#(Html.Kendo().Grid<CustomerLeadViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.CustomerName).Width(200);
columns.Bound(c => c.CustomerGroup);
columns.Bound(c => c.CustomerActivityField);
columns.Bound(c => c.AgentName);
columns.Command(command =>
{
command.Edit().Text("Edit");
command.Destroy().Text("Delete");
}).Width(250);
})
.HtmlAttributes(new { style = "height: 480px;" })
.Editable(editable => editable.Mode(GridEditMode.PopUp)).TemplateName("_CustomerEdit"))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(c => c.Id);
})
.Read(read => read.Action("Customers_Read", "CustomerLead", new { model = Model }))
.Update(update => update.Action("Customers_Update", "CustomerLead"))
.Destroy(delete => delete.Action("Customers_Destroy", "CustomerLead"))
)
)
and EditorTemplate/_CustomerEdit:
#model CustomerLeadViewModel
#Html.HiddenFor(model => model.Id)
#Html.Kendo().TextBoxFor(model => model.CustomerName)
#(
Html.Kendo().DropDownListFor(model=>model.CustomerGroupId)
.Name("CustomerGroup") //This name has to be the same as the Title on the main grid page
.DataTextField("GroupName")
.DataValueField("Id")
.DataSource(source =>
{
source.Read(read => { read.Action("GetCustomerGroups", "CustomerLead"); });
})
.OptionLabel("Select a group ...")
)
Controller:
public ActionResult Customers_Read([DataSourceRequest]DataSourceRequest request, CustomerLeadSearchViewModel model)
{
var customers = customerLeadRepository.Get(includeProperties: "CustomerSubGroup.CustomerGroup, CustomerActivityField");
if (model.CustomerName != null)
{
customers = customers.Where(c => c.CustomerName.Contains(model.CustomerName));
}
var customersViewModel = customers.Select(customer => new CustomerLeadViewModel
{
Id = customer.Id,
CustomerGroupId = customer.CustomerGroupId,
CustomerGroup = customer.CustomerSubGroup.CustomerGroup.GroupName,
CustomerName = customer.CustomerName,
CustomerActivityField = customer.CustomerActivityField.ActivityName,
AgentName = customer.AgentName,
Phone1 = customer.Phone1,
Mobile = customer.Mobile
});
return Json(customersViewModel.ToDataSourceResult(request));
}
public JsonResult GetCustomerGroups()
{
var customerGroups = customerGroupRepository.GetAll();
return Json(customerGroups.Select(c => new { Id = c.Id, GroupName = c.GroupName }), JsonRequestBehavior.AllowGet);
}
Model:
public class CustomerLeadViewModel
{
[ScaffoldColumn(false)]
public int Id { get; set; }
public string CustomerName { get; set; }
public string AgentName { get; set; }
public string Post { get; set; }
public string CustomerActivityField { get; set; }
public int CustomerGroupId { get; set; }
public string CustomerGroup { get; set; }
}
Change your _CustomerEditor template model field from
#(Html.Kendo().DropDownListFor(model=>model.CustomerGroupId)
to
#(Html.Kendo().DropDownListFor(model=>model.CustomerGroup)
Just as the comment says, "This name has to be the same as the Title on the main grid page"
The field that the DropDownListFor is binding to needs to be the same. Or, depending on your model, change them all to CustomerGroupId. Either way, they need to match.

How to bind the Kendo Grid in asp.net MVC 4 Razor

I have create the asp.net MVC 4 application where i am using the entity framework and class "Data" is the model.
AdventureWorksTrainingEntities _dbContext = new AdventureWorksTrainingEntities();
Data _data = new Data(); //Model
Now i want to display the data of the table to the kendo grid. In the controller, i am using the following code:
public ActionResult Index()
{
List<Movie> dataForGrid= _dbContext.Movies.ToList();
return View(dataForGrid);
}
Now i have no idea for displaying the data in Kendo Grid (i am new to kendo and MVC). I have also tried the following but not working:
#model IEnumerable<MvcApp.Models.Data>
#using Kendo.Mvc.UI
#{
ViewBag.Title = "Index";
}
<h2>Grid For Data</h2>
Html.Kendo().Grid<Order>()
.Name("Grid")
.DataSource(dataSource => dataSource // Not implemented
)
Finally got answer:
View:
#(Html.Kendo().Grid<KendoUI.Models.EmployeeViewModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.name).Title("Name");
columns.Bound(p => p.gender).Title("Gender");
columns.Bound(p => p.designation).Title("Designation").Width("300px");
columns.Bound(p => p.department).Title("Department").Width("300px");
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Navigatable()
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource // Configure the grid data source
.Ajax()
.Model(model =>
{
model.Id(x => x.id);
})
.Read(read => read.Action("Employee_Read", "Home")) // Set the action method which will return the data in JSON format
)
)
Controller:
public ActionResult Employee_Read([DataSourceRequest]DataSourceRequest request)
{
IQueryable<Bhupendra_employees> Details = _dbContext.Bhupendra_employees;
DataSourceResult result = Details.ToDataSourceResult(request, p => new EmployeeViewModel
{
id = p.id,
name = p.name,
gender = p.gender,
designation = p.designation,
department = p.Bhupendra_Dept.Dept_Description
});
return Json(result, JsonRequestBehavior.AllowGet);
}
Model:
public class EmployeeViewModel
{
public Int32 id { get; set; }
public String name { get; set; }
public String gender { get; set; }
public String designation { get; set; }
public String department { get; set; }
//public DateTime dob { get; set; }
}
if your controller name is Data then you can use the following
Your Model
public ActionResult ReadDegrees([DataSourceRequest] DataSourceRequest request)
{
ViewBag.Countries = CommonController.CountryList();
ViewBag.DegreeTypes = CommonController.DegreeTypeList();
using (var _dbContext= new AdventureWorksTrainingEntities ())
{
return Json(_dbContext.Movies.ToList.ToDataSourceResult(request));
}
}
Your View
Just you need to add the following assuming that your Model has a Key called ID
Html.Kendo().Grid<Order>()
.Name("Grid")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Model(model => model.Id(p => p.ID))
.Read(read => read.Action("ReadDegrees", "Data"))))

Why doesn't this Kendo Grid URL map to my controller action method?

I'm trying to follow the docs on how to make my kendo mvc grid ajaxified and able to support some in cell editing.
The problem I have is on save, I'm seeing the grid make the following request which is apparently not available. I'm not familiar with the models prefix stuff but it looks like the object is modeled in the URL properly with each property prefixed with &models, then some hash, then the parameter name and then the value.
Why doesn't this URL map to my controller action method?
"NetworkError: 404 Not Found -
http://localhost/MySite/UI/Orders/Update
?models%5B0%5D%5BId%5D=18c12470-0ca3-4e9c-b6d7-af1d6120e03f
&models%5B0%5D%5BNumber%5D=231413+
&models%5B0%5D%5BMod%5D=8ccbf70a-f368-434c-8c05-2e2f5278215d
&models%5B0%5D%5BModName%5D=M6G+++++++++++++++++++++++++++++++++++++++++++++++
&models%5B0%5D%5BDescription%5D=M6G+LMU+TTU1200
&models%5B0%5D%5BPart%5D=105442
&models%5B0%5D%5BPartDescription%5D=M6H+TELEMATICS+CONTROL+UNIT
&models%5B0%5D%5BQuantity%5D=20
&models%5B0%5D%5BDeliveryDate%5D=Tue+Apr+30+2013+00%3A00%3A00+GMT-0400+(Eastern+Daylight+Time)&_=1366818145016"
The Update method sig in the controller looks like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update([Kendo.Mvc.UI.DataSourceRequest] Kendo.Mvc.UI.DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<Order> order)
{
//do update
}
And the sample Order object looks like this
public class Order
{
public Guid Id { get; set; }
public string Number{ get; set; }
public Guid Mod{ get; set; }
public string ModName{ get; set; }
public string Description { get; set; }
public int Part{ get; set; }
public string PartDescription { get; set; } // View Model Purposes Only
[Required]
[UIHint("QuantityEditor")] //QuantityEditor is the name of the custom editor template
public int Quantity { get; set; }
public DateTime DeliveryDate{ get; set; }
}
Here's the grid code ala MVC:
#(Html.Kendo().Grid(Model)
.Name("my-grid")
.Columns(columns =>
{
columns.Bound(m => m.Id)
.Hidden(true)
.HtmlAttributes(new { #class = "some-class" });
columns.Bound(m => m.Mod)
.Hidden(true)
.HtmlAttributes(new { #class = "some-class" });
columns.Bound(m => m.ModName)
.Hidden(true)
.HtmlAttributes(new { #class = "some-class" });
columns.Bound(m => m.Description).HtmlAttributes(new { #class = "some-class" });
columns.Bound(m => m.Part).HtmlAttributes(new { #class = "part can-edit" });
columns.Bound(m => m.PartDescription).HtmlAttributes(new { #class = "can-edit" });
columns.Bound(m => m.DeliveryDate).Format("{0:yyyy-MM-dd}").HtmlAttributes(new { #class = "date can-edit" });
columns.Bound(m => m.Quantity).HtmlAttributes(new { #class = "quantity can-edit" }).FooterTemplate("Total:");
})
.Scrollable(s => s.Height("auto"))
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Events(events => events.DataBound("onDataBound"))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.Update(update => update.Action("Update", "Orders"))
.Read(read => read.Action("GetAllOrders", "Orders").Data("getAdditionalData"))
.Aggregates(aggregates => { aggregates.Add(p => p.Quantity).Sum(); })
.Model(model =>
{
model.Id(m => m.Id);
model.Field(m => m.Id).Editable(false);
model.Field(m => m.Part).Editable(true);
model.Field(m => m.Quantity).Editable(true);
model.Field(m => m.DeliveryDate).Editable(true);
model.Field(m => m.PartDescription).Editable(true);
})
)
)
At 1st glance it would look like,
.Read(read => read.Action("GetAllOrders", "Controller").Data("getAdditionalData"))
Instead of Controller you need to put in the actual name of the Controller so for example "PersonController" would be "Person".
Edit- Ok from the looks of it then you've setup your Read from datasource but not your Update and instead tried to do it in events.
http://demos.kendoui.com/web/grid/editing-inline.html
I find it easier not to use inline edits and instead create a template button to redirect to an edit page thus keeping the kendo related code simple.
Looks like your grid is being called from within an MVC area. If you have Areas setup within your MVC application, it's always a good practice to reference those when making calls with Kendo UI Widgets.
Below assumes an Area called "UI":
.Update(update => update.Action("Update", "Orders", new { Area = "UI" }))

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