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; }
}
}
Related
I am new to Kendo UI for ASP.NET MVC and I wanted to create a customized action button on a grid and retrieve some data when that button is clicked based on each unique row.
Here is my grid's code
#(Html.Kendo()
.Grid<PromotionVM>()
.Name("PromotionsGrid")
.Columns(columns =>
{
columns.Bound(c => c.Merchant);
columns.Bound(c => c.Item);
columns.Bound(c => c.Image);
columns.Bound(c => c.DiscountRate);
columns.Command(command => command.Custom("Approve").Click("ApprovePromotion"))
.Title("Action");
})
.DataSource(source =>
{
source.Ajax()
.Model(model => model.Id(field => field.Id))
.Read(read => read.Action("GetPromotions", "Promotion"));
})
)
Here is the PromotionVM:
[Required]
public Guid Id { get; set; }
public string Merchant { get; set; }
public string Branch { get; set; }
public string Item { get; set; }
public string Image { get; set; }
public decimal DiscountRate { get; set; }
and here is the javascript function that I want to call to do an ajax request
when I am able to get the "Id" column value from the Grid upon button click.
<script type="text/javascript">
function ApprovePromotion(e) {
}
</script>
Notice that the function is empty because I have no idea what to do here yet.
Please help if you can.
Thanks in advance.
Pretty open ended question, but as an example:
<script type="text/javascript">
function ApprovePromotion(e) {
e.preventDefault();
// grab data for row
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
// make ajax call
$.ajax({
url: '#Url.Action("MyAction", "MyController")',
type: "POST",
data: {
// pass data to controller parameters
ItemID: dataItem.Id,
OtherField: dataItem.OtherField
},
success: function (response) {
// On success do something. I'll switch to index
window.location.href = '#Url.Action("Index", "MyController")';
}
});
}
</script>
I'm developing a project with ASP MVC 5, Kendo UI, and some layers, but I'm struggling with how to display the drop-down list inside of an editable Grid, I followed this example:
Grid Editing / custom editor
However, I'm having serious issues because the drop-down list never appears, it's displaying two text boxes.
Also, if I run the Foreign Key column example:
Grid / ForeignKey column
I have a different result with a numeric up-down:
Besides, I tested this example from StackOverflow and the result is either two textboxes or the numeric up-down (it depends if I bound the column or I use the foreign key column):
dropdownlist in kendo grid not working
This is my code, in the Business Layer, I have these classes in order to return the Categories from the database:
using Test.DB.Operations;
using System.Collections.Generic;
using System.Linq;
namespace Test.Business
{
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
}
public class CategoryData
{
public static List<Category> GetCategories()
{
var catData = DatabaseService.GetEntities<DB.Category>().ToList();
return (from cData in catData select new Category() { ID = cData.ID, Name = cData.Name }).ToList();
}
}
}
Later, in my MVC Layer, the Controller populates the view with some methods like these ones:
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Test.Business;
using Test.Classes;
using Test.MVC.Classes;
using Test.MVC.Models;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace Test.MVC.Controllers
{
public class OrganizationDetailsController : Controller
{
public ActionResult Index(string ID)
{
PopulateCategories();
if (!string.IsNullOrEmpty(ID))
{
var model = new OrganizationsModel();
try
{
model.hasError = false;
model.messageBox = null;
}
catch (Exception ex)
{
model.hasError = true;
model.messageBox = new Tuple<string, string>("Error", "Please report it to the team");
}
return View(model);
}
else
{
return View();
}
}
public ActionResult OrganizationDetails_Read([DataSourceRequest]DataSourceRequest request, string ID)
{
try
{
var data = OrganizationDetailsData.GetOrganizationDetails(ID);
DataSourceResult result = data.ToDataSourceResult(request);
return Json(result);
}
catch (Exception ex)
{
return null;
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrganizationDetails_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]<OrganizationDetails> oDetails)
{
return null;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrganizationDetails_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<OrganizationDetails> oDetails)
{
return null;
}
private void PopulateCategories()
{
var dataContext = CategoryData.GetCategories();
ViewData["categories"] = dataContext;
ViewData["defaultCategory"] = dataContext[0];
}
}
}
The Model looks like this:
using Test.Business;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Test.MVC.Models
{
public class OrganizationsModel
{
public Tuple<string, string> messageBox;
public bool hasError;
}
}
Finally, in the View, I have this code for the Kendo Grid:
#(Html.Kendo().Grid<Test.Business.OrganizationDetails>()
.Name("gridDetails")
.Columns(columns =>
{
columns.Bound(b => b.Name);
columns.Bound(b => b.NumberOfEmployees);
//columns.ForeignKey(p => p.CategoryID, (System.Collections.IEnumerable)ViewData["categories"], "ID", "Name").Title("Categories").EditorTemplateName("dropdownTemplate");
columns.Bound(b => b.Category).ClientTemplate("#=Category.Name#");
columns.Bound(p => p.Telephone);
columns.Bound(p => p.Address);
})
.ToolBar(toolBar =>
{
toolBar.Create();
toolBar.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable()
.Sortable()
.Scrollable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.ID);
model.Field(p => p.ID).Editable(false);
model.Field(p => p.Category).DefaultValue(ViewData["defaultCategory"] as Test.Business.Category);
})
.PageSize(20)
.Read(read => read.Action("OrganizationDetails_Read", "OrganizationDetails").Data("LoadParams"))
.Create(create => create.Action("OrganizationDetails_Create", "Grid"))
.Update(update => update.Action("Organization_Update", "Grid"))
)
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
)
<input type="hidden" id="orgID" value="1" />
<script id="dropdownTemplate" type="text/x-kendo-template">
#(Html.Kendo().DropDownListFor(m => m)
.Name("myDropDown")
.DataValueField("ID")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["categories"])
)
</script>
<script type="text/javascript">
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
function LoadParams() {
var id = $("#orgID").val();
return { ID: id }
}
</script>
However, it's never working as it should be. Does anyone have experience this issue? And how did you manage it? Thanks for your ideas.
For the ForeignKey() implementation:
you have to put the "dropdownTemplate" in a cshtml file in Views/Shared/EditorTemplates. You cannot use a x-kendo-template because you are not using javascript initialization...you are using the razor helpers. What is likely happening to your is that you are specifying an non-existent EditorTemplate(no cshtml in Shared/EditorTemplates) so it just breaks.
Or, you can leave off the EditorTemplateName() altogether and Kendo will automatically use the EditorTemplate in Views/Shared/EditorTemplates/GridForeignKey.cshtml.
For the "ClientTemplate" implementation:
If you take a look at the full source code for the "Grid Editing / custom editor" example(in the examples that get installed with Kendo MVC), the EditorTemplate is specified using a UIHint on the model.
i.e. (using your classnames)
public class OrganizationDetails
{
...
[UIHint("ClientCategory")]
public CategoryViewModel Category {get; set;}
}
Then there must be a ClientCategory.cshtml file in Views/Shared/EditorTemplates that contains the razor for your editor implementation.
In the Kendo examples, ClientCategory.cshtml contains:
#model Kendo.Mvc.Examples.Models.CategoryViewModel
#(Html.Kendo().DropDownListFor(m => m)
.DataValueField("CategoryID")
.DataTextField("CategoryName")
.BindTo((System.Collections.IEnumerable)ViewData["categories"])
)
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"))))
I have got parent grid and child grid and I am using kendo UI Grid(Hierarchy grid format)
to bind the child grid data to corresponding row in parent grid for that I am able to show child grid for only first row and not able to show same details for another rows ...
This is my view for that grid ...
#model IEnumerable<KendoSampleMVCApp.Models.EmployeesDetailsModel>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#(Html.Kendo().Grid<KendoSampleMVCApp.Models.EmployeesDetailsModel>()
.Name("ParentGrids")
.Columns(columns =>
{
columns.Bound(e => e.EmployeeID).Width(100);
columns.Bound(e => e.EmployeeFirstName).Width(100);
columns.Bound(e => e.EmployeeSecondName).Width(100);
columns.Bound(e => e.EmployeeCity).Width(100);
})
.Sortable()
.Pageable()
.Scrollable()
.ClientDetailTemplateId("template")
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(5)
.Read(read => read.Action("HierarchyBinding_Employees", "HierarchyGridDisplay"))
)
)
<script id="template" type="text/kendo-tmpl">
#(Html.Kendo().Grid<KendoSampleMVCApp.Models.ShipDescriptionModel>()
.Name("ChildGrids")
.Columns(columns =>
{
columns.Bound(o => o.ShipAddress).Width(70);
columns.Bound(o => o.ShipCountry).Width(70);
columns.Bound(o => o.ShipName).Width(70);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(6)
.Read(read => read.Action("HierarchyBinding_Orders", "HierarchyGridDisplay"))
)
.Pageable()
.Sortable()
.ToClientTemplate()
)
</script>
<script>
function dataBound() {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
</script>
}
and this is my model
public class EmployeesDetailsModel
{
public string EmployeeID { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeeSecondName { get; set; }
public string EmployeeCity { get; set; }
}
public class ShipDescriptionModel
{
public string ShipCountry { get; set; }
public string ShipAddress { get; set; }
public string ShipName { get; set; }
}
public class EmployeeShipModel
{
public EmployeesDetailsModel employeesshipments { get; set; }
public ShipDescriptionModel shipinfo { get; set; }
}
would you pls suggest any ideas and any changes need to be done in view for showing child grid data to another rows as well... Many thanks
pls look at the images attached below
I believe that this is because you have a static id for the grid. You should try and give it a dynamic one, so different child grids can be created. This is why it only works on the first record, because you have no variation for the name of the grid.
Try to do this instead:
#(Html.Kendo().Grid<KendoSampleMVCApp.Models.ShipDescriptionModel>()
.Name("ChildGrid_#=EmployeeID#")
What is happening is that the EmployeeId from the parent grid is being pulled down, and being used for the naming convention of the grid. This way you can have as many child grids as like you like.
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()));
}