I'm looking to display two Telerik Kendo grids with different information(models) in one view and I'm not sure how to do it.
Model:
using System.Collections.Generic;
namespace KendoUIMvcApplication1.Models
{
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Truck
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Vehicles
{
public IEnumerable<Car> CarCol { get; set; }
public IEnumerable<Truck> TruckCol { get; set; }
}
}
Controller (Creating some test objects):
using System.Collections.Generic;
using System.Web.Mvc;
using KendoUIMvcApplication1.Models;
namespace KendoUIMvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var carList = new List<Car>();
var truckList = new List<Truck>();
var vehCol = new Vehicles();
var car1 = new Car
{
Id = 1,
Name = "Passat"
};
var car2 = new Car
{
Id = 2,
Name = "Passat"
};
carList.Add(car1);
carList.Add(car2);
var truck1 = new Truck
{
Id = 1,
Name = "S10"
};
var truck2 = new Truck
{
Id = 1,
Name = "Blazer"
};
truckList.Add(truck1);
truckList.Add(truck2);
vehCol.CarCol = carList;
vehCol.TruckCol = truckList;
return View(vehCol);
}
}
}
View (Here I'm trying to display the two grids. The first one for cars and the second one for trucks):
#using KendoUIMvcApplication1.Models
#model IEnumerable<Vehicles>
#*// Car Grid*#
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns => {
columns.Bound(c => c.Id);
columns.Bound(c => c.Name);
})
)
<div></div>
#*// Truck Grid*#
#(Html.Kendo().Grid(Model))
.Name("Grid")
.Columns(columns => {
columns.Bound(t => t.Id);
columns.Bound(t => t.Name);
})
)
Your model should be of type Vehicles:
#model Vehicles
Then you can access the two collections:
#Html.Kendo().Grid(Model.CarCol)
...
and
#Html.Kendo().Grid(Model.TruckCol)
...
Related
I am using MVC 5 with Kendo UI(Latest Version) and SQL Server 2014, and I want to add a treeview controller that will display parent items and child items when users click on the parent item. I have two classes:
1.Category
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProductTreeView.Models
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
}
2.Product
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProductTreeView.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
}
}
My controller action looks like this:
public ActionResult Products(int? id)
{
var model = db.Categories
.Select(p => new {
id = p.Id,
Name = p.Name,
hasChildren = p.Products.Any()
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
And the HTML looks like this:
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="row">
<div class="col-md-3">
<label class="k-label-top">TreeView</label>
#(Html.Kendo().TreeView().Name("treeview")
.DataSource(datasource => datasource
.Read(read => read.Action("Products", "Categories"))
).DataTextField("Name")
)
</div>
</div>
The result is parent items within parent items, looping.
Results
That is a self referencing example you might use for employees/managers. You need the more classical way where you provide the child products in a collection.
public ActionResult Products(int? id)
{
var model = db.Categories
.Select(p => new {
id = p.Id,
Name = p.Name,
hasChildren = p.Products.Any(),
Children = p.Products
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
Then something like:
#(Html.Kendo().TreeView().Name("treeview")
.DataSource(d => d
.Model(m => m
.Id("Id")
.HasChildren("hasChildren")
.Children("Children"))
.Read(r => r.Action("Products", "Categories")))
.DataTextField("Name"))
http://demos.telerik.com/kendo-ui/treeview/local-data-binding
I have a very special problem and wasn't yet able to find anything to help me solving it.
I have a form which has a bunch of textboxes, dropdownlists and such which are posted back through the model attached in the view. However I also have a Grid which is dynamically populated through one of the DropDownLists. I want to parse the whole grid back to the forms-controller, but I have no clue how to do that.
An ajax-post doesn't work, because I have no access to the actual model. The only thing I could do is post the controls-values itself, but that approach is somewhat messy.
The model itself has a variable "Mappings" which is of the Type IEnumerable. This is the type I also bind to the grid. So there should be a way to somehow add the mappings inside of the grid to the model. I thought it might work automatically if I name the grid like the name of the property inside of the main model ("Mappings"), but that didn't work. So I am yet again back to square one.
Maybe you guys have an idea how to solve my Problem as I am somewhat out of ideas.
View:
#using (Html.BeginForm("Save", "Profile", FormMethod.Post, new { Id = "addProfileForm", novalidate = "false" }))
{
<ul id="progressbar">
<li class="active">Grundeinstellungen</li>
<li>CRM-Einstellungen</li>
<li>Mapping anlegen</li>
</ul>
<fieldset>
<h2 class="fs-title">Grundinformationen</h2>
#Html.LabelFor(model => model.Name, new { #class = "label req" })
#Html.TextBoxFor(model => model.Name, new { #class = "input" })
#Html.LabelFor(model => model.Description, new { #class = "label" })
#Html.TextAreaFor(model => model.Description, new { #class = "input", rows = "3", cols = "25" })
#Html.LabelFor(model => model.UserGroupId, new { #class = "label req" })
#(Html.Kendo().DropDownListFor(model => model.UserGroupId)
.OptionLabel("Bitte auswählen... ")
.BindTo(Model.UserGroupList)
)
<input type="button" name="next" class="next action-button" value="Weiter" style="display:block"/>
</fieldset>
<fieldset>
<h2 class="fs-title">CRM-Einstellungen</h2>
#Html.LabelFor(model => model.OrdnungsbegriffTypeId, new { #class = "label req" })
#(Html.Kendo().DropDownListFor(model => model.OrdnungsbegriffTypeId)
.OptionLabel("Bitte auswählen...")
.BindTo(Model.OrdnungsbegriffTypeList)
)
#Html.LabelFor(model => model.CrmTypeId, new { #class = "label req" })
#(Html.Kendo().DropDownListFor(model => Model.CrmTypeId)
.Name("CrmTypeId")
.OptionLabel("Bitte auswählen...")
.BindTo(Model.CrmTypeList)
.Events(e =>
e.Select("onCrmTypeSelect"))
)
<br />
<input type="button" name="previous" class="previous action-button" value="Zurueck" />
<input type="button" name="next" class="next action-button" value="Weiter" />
</fieldset>
<fieldset>
<h2 class="fs-title">Mapping anlegen</h2>
#(Html.Kendo().Upload()
.Name("upMappingFile")
.Multiple(false)
.ShowFileList(true)
.TemplateId("fuCsvTemplate")
.Async(a => a
.AutoUpload(true)
.Save("SaveFile", "Mapping")
.Remove("RemoveFile", "Mapping")
)
.Enable(false)
.Events(e => e
.Success("onSuccess"))
.Messages(m => m
.Select("Durchsuchen...")
.HeaderStatusUploading("Uploading...")
.HeaderStatusUploaded("Fertig"))
)
<div id="gridContainer">
</div>
<div id="appendTo" class="k-block"></div>
<input type="button" name="previous" class="previous action-button" value="Zurueck" />
<input type="submit" name="submit" class="submit action-button" value="Speichern"/>
</fieldset>
#Html.Kendo().Notification().Name("crmTypeNotification")
}
Ajax-Post for dynamically creating the grid:
function onSuccess(e) {
var gridNotification = $("#gridNotification").data("kendoNotification");
var crmType = $("#CrmTypeId").data("kendoDropDownList");
var csvHeadRow = e.response.csvHeadRow
var url = '#Url.Action(MVC.Mapping.ReturnMappingGrid())';
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ csvHead: csvHeadRow, crmType: crmType.text() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#gridContainer').html(data);
gridNotification.show("Die Auswahl der jeweiligen Eigenschaft erfolgt durch Klicken des jeweiligen Eigenschaft-Felds!")
var container = $(gridNotification.options.appendTo);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
debugger;
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
},
async: false
});
}
Partial View Grid:
#(Html.Kendo().Grid<DAKCrmImportModel.Model.Entities.Base.CrmMapping>().Name("Mappings").BindTo(Model)
.Columns(c =>
{
c.Bound(m => m.CsvColumn).Title("Spalte").Width(300);
c.Bound(m => m.CrmProperty).EditorTemplateName("PropertyId");
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(m =>
{
m.Id(ma => ma.Id);
m.Field(ma => ma.Id).Editable(false);
})
)
)
CrmProfile-model:
public class CrmProfile
{
public CrmProfile()
{
this.Mappings = new HashSet<CrmMapping>();
this.Jobs = new HashSet<CrmJob>();
}
[Column(Order = 1)]
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Bezeichnung")]
public string Name { get; set; }
[Display(Name = "Beschreibung")]
public string Description { get; set; }
[Required]
public string CreatedBy { get; set; }
[Column(Order = 2)]
[ForeignKey("UserGroup")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[Required]
[Display(Name = "Usergruppe")]
public int UserGroupId { get; set; }
public UserGroup UserGroup { get; set; }
[Column(Order = 3)]
[ForeignKey("CrmType")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[Required]
[Display(Name = "Einspielungstyp")]
public int CrmTypeId { get; set; }
public CrmImportType CrmType { get; set; }
[Column(Order = 4)]
[ForeignKey("OrdnungsbegriffType")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[Required]
[Display(Name = "Ordnungsbegrifftyp")]
public int OrdnungsbegriffTypeId { get; set; }
public OrdnungsbegriffType OrdnungsbegriffType { get; set; }
public byte[] SourceFile { get; set; }
public string SourceFileName { get; set; }
public string[] SourceFileHeadRow { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
public string LastUpdatedBy { get; set; }
public DateTime? LastUpdatedAt { get; set; }
public DateTime? LastUsedAt { get; set; }
public ICollection<CrmMapping> Mappings { get; set; }
public ICollection<CrmJob> Jobs { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> UserGroupList { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> CrmTypeList { get; set; }
[NotMapped]
public IEnumerable<SelectListItem> OrdnungsbegriffTypeList { get; set; }
}
CrmMapping-model:
public class CrmMapping
{
[Key]
[Column(Order = 0)]
public int Id { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[ForeignKey("Profile")]
public int ProfileId { get; set; }
public CrmProfile Profile { get; set; }
[Required]
public string CrmProperty { get; set;}
[Required]
public string CsvColumn { get; set; }
[Required]
public int CsvIndex { get; set; }
[UIHint("PropertyId")]
[NotMapped]
public int PropertyId { get; set; }
[NotMapped]
public IEnumerable<CrmProperty> CrmProperties { get; set; }
}
[UPDATE]
I want to post the grid-data back with ajax, but I don't seem to get the right datatype on serverside.
function postProfileData() {
var url = '/Profile/Save';
$.ajax({
type: "POST",
url: url,
data: $("#addProfileForm").serialize() + "&Mappings=" + getMappings(),
success: function (data) {
debugger;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
debugger;
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
},
async: false
});
}
function getMappings() {
var grid = $("#Mappings").data("kendoGrid");
debugger;
return grid._data;
}
[HttpPost]
public virtual ActionResult Save(CrmProfile crmProfile, List<CrmMapping> Mappings)
{
using (DAKCrmImportContext db = new DAKCrmImportContext())
{
crmProfile.CreatedAt = DateTime.Now;
crmProfile.CreatedBy = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
try
{
db.CrmProfiles.Add(crmProfile);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
var vals = e.EntityValidationErrors;
throw;
}
}
return RedirectToAction("Add", "Mapping", crmProfile);
}
[UPDATE2] So the problem is likely that JavaScript doesn't like my Listtype (CrmMapping) and doesn't know what to do with it. I'm not quite sure why, but I think its's because its structure doesn't fit the normal id:value pair. Maybe the problem is that Id is 0 in all ListItems and I'll have to fill it manually, but CrmMapping is actually a model-class so I'd have to set it back to 0 eventually so I'd probably have to create a ViewModel just to parse the grid-data back.
public class CrmMapping
{
[Key]
[Column(Order = 0)]
public int Id { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None)]
[ForeignKey("Profile")]
public int ProfileId { get; set; }
public CrmProfile Profile { get; set; }
[Required]
public string CrmProperty { get; set;}
[Required]
public string CsvColumn { get; set; }
[Required]
public int CsvIndex { get; set; }
[UIHint("PropertyId")]
[NotMapped]
public int PropertyId { get; set; }
[NotMapped]
public IEnumerable<CrmProperty> CrmProperties { get; set; }
}
Since you're creating the grid from the #model instead of using ajax calls for the datasource.Read, you could just create hidden inputs using a for loop, and as long as they're in the form tag they would post back.
Something like
#(Html.Kendo().Grid<DAKCrmImportModel.Model.Entities.Base.CrmMapping>().Name("Mappings").BindTo(Model)
.Columns(c =>
{
c.Bound(m => m.CsvColumn).Title("Spalte").Width(300);
c.Bound(m => m.CrmProperty).EditorTemplateName("PropertyId");
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Model(m =>
{
m.Id(ma => ma.Id);
m.Field(ma => ma.Id).Editable(false);
})
)
)
#for (int i = 0; i < Model.Count; i++)
{
#Html.Hidden("Mappings[" + i.ToString() + "].Id", Model[i].Id)
#Html.Hidden("Mappings[" + i.ToString() + "].CsvColumn", Model[i].CsvColumn)
#Html.Hidden("Mappings[" + i.ToString() + "].CrmProperty", Model[i].CrmProperty)
}
If you edit any of the columns, the new values won't get posted back using this method so you should probably wire up the ajax datasource events to Read, Create, Edit and Delete if you want to be able to maintain the grid data correctly
Ok, after trying a bunch of things I finally found a solution. To do this I need a javscript-expension:
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
This is needed to serialize the form as an object instead of posting the form itself.
The next thing we have to do is create a ViewModel which has properties for the model of the form we want to submit/post and the additional data we want to get into the controller-action.
using DAKCrmImportModel.Model.Entities.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DAKCrmImport.Models
{
public class CrmProfileAddVM
{
public CrmProfile Profile { get; set; }
public CrmMapping[] Mappings { get; set; }
}
}
We have to declare CrmMapping as Array here, because thats the datatype the Telerik-grid uses.
Now let's do the ajax-function which contains our ViewModel with the form-data (Profile) and the grid._data (Mappings).
function postProfileData() {
var url = '#Url.Action(MVC.Profile.Save())';
$.ajax({
type: "POST",
url: url,
//.serialize()
//data: $("#addProfileForm").serialize(), "crmMappingList": getMappings(),
contentType: 'application/json',
data: JSON.stringify({
Profile: $("form#addProfileForm").serializeObject(),
Mappings: getMappings()
}),
//data: { Mappings: getMappings() },
success: function (data) {
debugger;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
debugger;
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
},
async: false
});
}
function getMappings() {
var grid = $("#Mappings").data("kendoGrid");
return grid._data;
}
Finally the last thing we have to do is change the controller-Action Parameter so that we have access to the instance of our ViewModel.
[HttpPost]
public virtual ActionResult Save(CrmProfileAddVM model)
{
using (DAKCrmImportContext db = new DAKCrmImportContext())
{
//crmProfile.CreatedAt = DateTime.Now;
//crmProfile.CreatedBy = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
//try
//{
// db.CrmProfiles.Add(crmProfile);
// db.SaveChanges();
//}
//catch (DbEntityValidationException e)
//{
// var vals = e.EntityValidationErrors;
// throw;
//}
}
return RedirectToAction("Add", "Mapping", null);
}
I am trying to setup kendo mvc ui grid using local data and make it sortable as in this demo Binding to local data.
However grid doesn't show data and if I hook up the onDataBound event, data inside there is undefined.
If I comment out DataSource setup on view, data gets populated at first, but disappears after sorting performed on any column.
I am using Kendo UI version: "2013.3.1119", asp.net mvc 4.
Please advice.
Thanks.
view
#model TestViewModel
#(Html.Kendo().Grid(Model.TestList)
.Name("grid2")
.Columns(columns =>
{
columns.Bound( p => p.Id ).Title( "ID" );
columns.Bound( p => p.Name ).Title("Product Name");
})
.Pageable()
.Sortable()
.Scrollable(scr=>scr.Height(430))
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false))
)
controller and model
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
var mdl = new TestViewModel();
mdl.TestList = Test().ToList();
return View(mdl);
}
public IEnumerable<TestMe> Test()
{
var lst = new List<TestMe>();
for( int i = 0; i < 5; i++ )
{
lst.Add( new TestMe
{
Id = i,
Name = i.ToString(),
} );
}
return lst;
}
}
public class TestViewModel
{
public List<TestMe> TestList { get; set; }
public TestViewModel()
{
TestList = new List<TestMe>();
}
}
public class TestMe
{
public int Id { get; set; }
public string Name { get; set; }
}
I created a view that was working wonderfully until I added some JQuery to support cascading drop downs. I believe in doing that, I broke the binding between the view and the model. I'm getting the error "No parameterless constructor defined for this object." when the form is submitted. The obvious solution would be to add a parameterless constructor, but I'm assuming that the postmodel will be null? Code Snippets below.
Thanks in Advance for your help.
View:
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCategories").change(function () {
var iCategoryId = $(this).val();
$.getJSON(
"#Url.Content("~/Remote/SubCategoriesByCateogry")",
{ id: iCategoryId },
function (data) {
var select = ResetAndReturnSubCategoryDDL();
$.each(data, function (index, itemData) {
select.append($('<option/>', { value: itemData.Value, text: itemData.Text }));
});
});
});
function ResetAndReturnSubCategoryDDL() {
var select = $('#ddlSubCategory');
select.empty();
select.append($('<option/>', { value: '', text: "--Select SubCategory--" }));
return select;
}
});
...
<div class="editor-field">
#Html.DropDownList("iCategoryID", Model.Categories,"--Select Category--", new Dictionary<string,object>{ {"class","dropdowns"},{"id","ddlCategories"}})
#Html.ValidationMessage("iCategoryID")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SubCategories, "SubCategory")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SubCategories, new SelectList(Enumerable.Empty<SelectListItem>(), "iSubCategoryID", "SubCategory",Model.SubCategories), "--Select SubCategory--", new { id = "ddlSubCategory" })
#Html.ValidationMessage("iSubCategoryID")
</div>
Controller:
[HttpPost]
public ActionResult Create(VendorCreateModel postModel)
{
VendorCreateEditPostValidator createValidator = new VendorCreateEditPostValidator(
postModel.iCategoryID,
postModel.iSubCategoryID,
postModel.AppliedPrograms,
m_unitOfWork.ProgramRepository,
new ModelStateValidationWrapper(ModelState));
if (ModelState.IsValid)
{
int categoryId = int.Parse(postModel.iCategoryID);
int subcategoryId = int.Parse(postModel.iSubCategoryID);
var programIds = postModel.AppliedPrograms.Select(ap => int.Parse(ap));
var programs = m_unitOfWork.ProgramRepository.GetPrograms(programIds);
Vendor vendor = postModel.Vendor;
vendor.Category = m_unitOfWork.CategoryRepository.GetCategory(categoryId);
vendor.SubCategory = m_unitOfWork.SubCategoryRepository.GetSubCategory(subcategoryId);
foreach (Program p in programs)
vendor.Programs.Add(p);
m_unitOfWork.VendorRepository.Add(vendor);
m_unitOfWork.SaveChanges();
return RedirectToAction("Index");
}
VendorCreateModel model = new VendorCreateModel(
postModel.Vendor,
postModel.iCategoryID,
postModel.iSubCategoryID,
postModel.AppliedPrograms,
User.Identity.Name,
m_unitOfWork.CategoryRepository,
m_unitOfWork.SubCategoryRepository,
m_unitOfWork.PermissionRepository);
return View(model);
}
RemoteController:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult SubCategoriesByCateogry(int id)
{
System.Diagnostics.Debug.WriteLine(id);
var SubCategories = db.SubCategories
.Where(v => v.iCategoryID == id)
.OrderBy(v => v.sDesc)
.ToList();
var modelData = SubCategories.Select(v => new SelectListItem()
{
Text = v.sDesc,
Value = v.iSubCategoryID.ToString()
});
return Json(modelData, JsonRequestBehavior.AllowGet);
}
VendorCreateModel:
public class VendorCreateModel
{
public VendorCreateModel()
{
}
public VendorCreateModel(
Vendor vendor,
string categoryId,
string subcategoryId,
IEnumerable<string> appliedPrograms,
string username,
ICategoryRepository categoryRepository,
ISubCategoryRepository subcategoryRepository,
IPermissionRepository permissionRepository)
{
UserHasProgramsValidator programValidator = new UserHasProgramsValidator(username, permissionRepository);
var availablePrograms = programValidator.AvailablePrograms;
HashSet<Category> applicableCategories = new HashSet<Category>();
foreach (var p in availablePrograms)
foreach (var c in categoryRepository.GetCategoriesByProgram(p.iProgramID))
applicableCategories.Add(c);
this.Vendor = vendor;
this.AppliedPrograms = appliedPrograms;
this.Categories = new SelectList(applicableCategories.OrderBy(x => x.sDesc).ToList(), "iCategoryID", "sDesc");
this.SubCategories = new SelectList(subcategoryRepository.GetAllSubCategories().OrderBy(x => x.sDesc).ToList(), "iSubCategoryID", "sDesc");
if (!string.IsNullOrEmpty(categoryId))
{
int temp;
if (!int.TryParse(categoryId, out temp))
throw new ApplicationException("Invalid Category Identifier.");
}
this.iCategoryID = categoryId;
this.iSubCategoryID = subcategoryId;
this.ProgramItems = availablePrograms
.Select(p => new SelectListItem()
{
Text = p.sDesc,
Value = p.iProgramID.ToString(),
Selected = (AppliedPrograms != null ? AppliedPrograms.Contains(p.iProgramID.ToString()) : false)
});
}
public Vendor Vendor { get; set; }
public SelectList Categories { get; set; }
public SelectList SubCategories { get; set; }
public string iCategoryID { get; set; }
public string iSubCategoryID { get; set; }
public IEnumerable<SelectListItem> ProgramItems { get; set; }
[AtLeastOneElementExists(ErrorMessage = "Please select at least one program.")]
public IEnumerable<string> AppliedPrograms { get; set; }
}
I correct the issue and wanted to share in case someone else was banging their head against their desk like Ihave been. Basically I changed the dropdownlistfor to reflect:
#Html.DropDownListFor(model => model.iSubCategoryID, new SelectList(Enumerable.Empty<SelectListItem>(), "iSubCategoryID", "SubCategory",Model.SubCategories), "--Select SubCategory--", new Dictionary<string,object>{ {"class","dropdowns"},{"id","ddlSubCategory"},{"name","iSubCategoryID"}})
Assuming here the problem is in your VendorCreateModel, you either need to add a parameterless constructor or remove it, and create an instance in your action method and populate it by TryUpdateModel. Or parse the form using FormsCollection (not a fan).
You don't have the code for your viewmodel posted here but the basic assumption is that it will map.
I want to have a dropdownlist in my view that displays a patient's ID, First Name, and Last Name. With the code below, it displays each patient's First Name. How can I pass all three properties into the viewbag and have them display in the dropdownlist?
Controller
public ActionResult Create()
{ViewBag.Patient_ID = new SelectList(db.Patients, "Patient_ID", "First_Name");
return View();
}
View
<div class="editor-field">
#Html.DropDownList("Patient_ID", String.Empty)
#Html.ValidationMessageFor(model => model.Patient_ID)
</div>
Thanks.
Ok, I have edited my code as follows, and I receive the error "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedPatientId'."
Controller
public ActionResult Create()
{
var model = new MyViewModel();
{
var Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
var Prescribers = db.Prescribers.ToList().Select(p => new SelectListItem
{
Value = p.DEA_Number.ToString(),
Text = string.Format("{0}-{1}-{2}", p.DEA_Number, p.First_Name, p.Last_Name)
});
var Drugs = db.Drugs.ToList().Select(p => new SelectListItem
{
Value = p.NDC.ToString(),
Text = string.Format("{0}-{1}-{2}", p.NDC, p.Name, p.Price)
});
};
return View(model);
}
View Model
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
[Required]
public int? SelectedPrescriber { get; set; }
public IEnumerable<SelectListItem> Prescribers { get; set; }
[Required]
public int? SelectedDrug { get; set; }
public IEnumerable<SelectListItem> Drugs { get; set; }
}
View
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
#Html.DropDownListFor(
x => x.SelectedPrescriber,
Model.Patients,
"-- Select prescriber ---"
)
#Html.ValidationMessageFor(x => x.SelectedPrescriber)
<button type="submit">OK</button>
}
I would recommend you not to use any ViewBag at all and define a view model:
public class MyViewModel
{
[Required]
public int? SelectedPatientId { get; set; }
public IEnumerable<SelectListItem> Patients { get; set; }
}
and then have your controller action fill and pass this view model to the view:
public ActionResult Create()
{
var model = new MyViewModel
{
Patients = db.Patients.ToList().Select(p => new SelectListItem
{
Value = p.Patient_ID.ToString(),
Text = string.Format("{0}-{1}-{2}", p.Patient_ID, p.First_Name, p.Last_Name)
});
};
return View(model);
}
and finally in your strongly typed view display the dropdown list:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.SelectedPatientId,
Model.Patients,
"-- Select patient ---"
)
#Html.ValidationMessageFor(x => x.SelectedPatientId)
<button type="submit">OK</button>
}
Easy way to accomplish that is just creating additional property on your model either by modifying model class or adding/modifying a partial class
[NotMapped]
public string DisplayFormat
{
get
{
return string.Format("{0}-{1}-{2}", Patient_ID, First_Name, Last_Name);
}
}