Populate Result Set in SelectList MVC3 - c#

I have following SelectList declaration in CourseRegisterModel:
public class CourseRegisterModel
{
public StudentModel Student { get; set; }
public CourseModel Course { get; set; }
public IEnumerable<SelectListItem> CoursesList { get; set; }
public DateTime RegisterDate { get; set; }
}
In CourseController I am retrieving all available courses by calling wcf web service:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
List<CourseModel> modelList = new List<CourseModel>();
foreach (var serviceCourse in courses)
{
CourseModel model = new CourseModel();
model.CId = serviceCourse.CId;
model.Code = serviceCourse.Code;
model.Name = serviceCourse.Name;
model.Fee = serviceCourse.Fee;
model.Seats = serviceCourse.Seats;
modelList.Add(model);
}
return View(modelList);//RegisterCourses.chtml
}
I need to populate these courses in a dropdown on view RegisterCourses.chtml. How to put all records in selectlist in above code? Also how would i use that selectlist on view?

For starters, your RegisterCourses.cshtml needs to use:
#model <namespace>.CourseRegisterModel
Then, your controller code would be:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
CourseRegisterModel model = new CourseRegisterModel();
//model = other model population here
model.CourseList = courses.Select(sl => new SelectListItem()
{ Text = sl.Name,
Value = sl.CId })
.ToList();
return View(model);
}
And finally, back to your view (RegisterCourses.cshtml) - it should contain:
#Html.DropDownListFor(m => m.Course.CId, Model.CourseList)

Use the Html.DropDownList method: http://msdn.microsoft.com/en-us/library/dd492738(v=vs.108).aspx
Pass in the desired name of the drop down list as first argument, as second argument pass in your CourseList:
#Html.DropDownList("CoursesList", Model.CoursesList)

Related

how to use ICollection for SelectList in Contoller of MVC?

I am developing .NET MVC application.
I want to send the collection of the objects from controller to View using select list.
without using view bag.
ViewModel :
public class AdviceCreateVM
{
public int Id { get; set; }
public string AdviceNo { get; set; }
public ICollection<CompanyVM> Companies { get; set; }
}
public class CompanyVM
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller Code :
public class AdviceCreateController : Controller
{
public ActionResult Create()
{
adviceVM.Companies = new SelectList(ledgerService.GetAll().OrderBy(t => t.Name), "Id", "Name");
}
}
It gives an error -
Cannot implicitly convert type 'System.Web.Mvc.SelectList' to
'System.Collections.Generic.ICollection'. An
explicit conversion exists (are you missing a cast?)
You're trying to assign a SelectList to property of type ICollection<CompanyVM> -- which won't work. You need some like:
var viewModel = new AdviceCreateVM
{
adviceVM.Companies =
ledgerService.GetAll().OrderBy(t => t.Name)
.Select(t=>
new CompanyVM
{
Id = t.Id, // "Id"
Name = t.Name // "Name"
})
.ToList()
};
I'm just guessing on the assignments here, since you didn't specify them.
In the view, you will have to make the select list from Companies property.
#Html.DropDownListFor(model => model.CompanyId,
model.Companies.Select(company =>
new SelectListItem
{
Value = company.Id,
Text = company.Name
}), "--Select Company--")
As indicated in the comments, SelectList does not implement ICollection. Change you view model collection to SelectList
public class AdviceCreateVM
{
public int Id { get; set; }
public string AdviceNo { get; set; }
public SelectList Companies { get; set; } // change to select list
public int CompanyID { get; set; } // for binding the the drop down list
}
Controller
public ActionResult Create()
{
AdviceCreateVM model = new AdviceCreateVM(); // initialise model
model.Companies = new SelectList(ledgerService.GetAll().OrderBy(t => t.Name), "Id", "Name");
}
View
#model YourAssembly.AdviceCreateVM
#using (Html.BeginForm()) {
....
#Html.DropDownFor(m => m.CompanyID, Model.Companies)
...

Using a model to create a drop down list

Asp.net MVC 4
Entity Framework 5
LINQ
C#
I have a ViewModel I am using already. I am now adding my PermissionType model to my ViewModel.
This model represents a table in the database with the same name.
How do I turn this table into a #Html.DropDownListFor()
From the table for the 'text' I need 'name' from the database.
From the table for the 'value' I need 'ID' from the database.
How do I turn that model into a usable drop down list from my controller to my page?
ForumBoard model = new ForumBoard();
model.TPGForumQuery = db.TPGForums;
model.ProPit_User = db.ProPit_User.Where(m => m.username == userName).FirstOrDefault();
model.TPGForumTopicQuery = db.TPGForumTopics;
// need help here
model.PermissionType = // a list of all of the permission in this table
Edit:
public class ForumBoard
{
public ForumBoard()
{
this.ProPit_User = new ProPit_User();
this.TPGForum = new TPGForum();
this.PermissionType = new List<ListItem>();
}
List<ListItem> PermissionType { get; set; }
public virtual IEnumerable<TPGForum> TPGForumQuery { get; set; }
public virtual ProPit_User ProPit_User { get; set; }
public virtual IEnumerable<TPGForumTopic> TPGForumTopicQuery { get; set; }
public virtual TPGForum TPGForum { get; set; }
}
First, Change your view model
class ForumBoard
{
...
public IEnumerable<ListItem> PermissionType {get; set;}
...
}
Then, assign
ForumBoard model = new ForumBoard();
...
model.PermissionType = db.PermissionType
.Select(p=>
new ListItem (){ Text = p.FieldForText,
Value= p.FieldForValue });
Edit: If your fields are non string type, unfortunately, you have to first call ToList() method.
model.PermissionType = db.PermissionType
//.Select(p => new {Text = p.TextField, Value = p.permissionID })
.ToList()
.Select(p=> new ListItem (){
Text = p.Text.ToString(),
Value= p.Value.ToString()});
You can try this method :
//Controller :
using(MyContext context = new MyContext() )
{
IEnumerable<SelectListItem> listItems = context.PermissionType.Select( p => new SelectListItem{ Text = p.FieldNameFor , Value = p.FieldNameFor });
ViewBag.myList = listItems;
}
/*
Do other stuffs here and then return to View()
*/
// In your view :
#{
IIEnumerable<SelectListItem> listItems = (IEnumerable<SelectListItem>)ViewBag.myList;
}
#Html.DropDownListFor("Name of DropDownList" , listItems )

Dropdownlist issue in razor

hi all i have a controller
public ActionResult Search(FormCollection collection)
{
....
var column = new Models.ColumnMapping("CTR");
ViewData["ColoumName"] = column;
var search = new Models.Search(columnname,searchvalue);
return View(search);
}
my view data contains following model property value..
public class Column {
public string ColumnName { get; set; }
public DataTypes DataType { get; set; }
}
i have to create a drop down list for ColumnName(all data contain in VIewData) and my view is like
#Html.DropDownListFor("clname", ViewData["ColoumName"] as IEnumerable<AML.Web.Models.Column>, "ColumnName", "ColumnName"))
but this is not working
Try like this, This is just an example.
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
Controller
public ActionResult CustomerInfo()
{
ViewBag.CustomerNameID = new SelectList(new[]
{
new {ID="1",Name="name1"},
new{ID="2",Name="name2"},
new{ID="3",Name="name3"},
},"ID", "Name");
return View();
}
Model
public Class ViewModel {
public int CustomerId { get; set; }
}
If you have to use #Html.DropDownListFor then it should like this #Html.DropDownListFor(m => m.CustomerId ,(List<SelectList>)ViewBag.CustomerNameID,"-- Select --", new { #class = "input-block-level" })
instead of DropDownListFor try DropDownList with SelectList().
#Html.DropDownList("clname",
new SelectList((IEnumerable) ViewData["ColoumName"], "Id", "ColoumName"))

Populate Data in DropDownList in Create Mode MVC 4

I'm trying to populate data from table in DropDownList using MVC4. Trying to figure it out how to get all the languages' titles into the DropDown in the Edit mode.
Models:
public class CategoryLanguage
{
public int ID { get; set; }
public int LanguageID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
public class Language
{
public int ID { get; set; }
public string Title { get; set; }
}
Controller:
public ActionResult Create()
{
using (MyDBContext db = new MyDBContext())
{
ViewBag.ID = new SelectList(db.Languages, "ID", "Title");
return View();
}
}
//
// POST: /Emp/Create
[HttpPost]
public ActionResult Create(CategoryLanguage newCatLang)
{
using (MyDBContext db = new MyDBContext())
{
if (ModelState.IsValid)
{
db.CategoryLanguages.Add(newCatLang);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ID = new SelectList(db.Languages, "ID", "Title", newCatLang.LanguageID);
return View(newCatLang);
}
}
View:
#model MultilanguageCategories.CORE.Models.CategoryLanguage
#{
ViewBag.Title = "Create";
}
<h2>Add New Item</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.DropDownList("ID", "--Select--")
}
Trying to figure it out how to get all the languages' titles into the DropDown when creating new CategoryLanguage entity. The error says: "The operation cannot be completed because the DbContext has been disposed." and this line marked: #Html.DropDownList("ID", "--Select--")
Change your get method "Create" as mentioned below :
public ActionResult Create()
{
var languages = new List<Language>();
using (MyDBContext db = new MyDBContext())
{
languages = db.Languages.ToList();
}
ViewBag.ID = new SelectList(languages, "ID", "Title");
return View();
}
Now you can use DropDownListFor as mentioned below :
#Html.DropDownListFor(model => model.[PropertyName], (IEnumerable<SelectListItem>)ViewBag.ID)
you're close...
You need to Add the languages select list to the viewbag (which you've already done, but with a badly named key)
ie: ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");
if you want an empty field that's easy enough too:
var langs = db.Languages.ToList().ConvertAll(x => new SelectListItem() { Value = x.ID, Text = x.Title });
langs.Insert(0, new SelectListItem() { Value = "", Text = "--Select--" });
ViewBag.LanguagesList = langs;
The DropdownList should be for a property in the model.
#Html.DropDownListFor(m => m.LanguageID, (IEnumerable<SelectListItem>)ViewBag.LanguagesList)
As it looks like you are using an Entity Framework class as your model you need to ensure the context is not disposed before the view is rendered.
As Per Microsoft's example link instantiate the context at the top of the controller, and drop the using statement in the Create method.
ie :
public class LanguageCategoryController : Controller
{
MyDBContext db = new MyDBContext();
public ActionResult Create()
{
ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");
// or replace the above line with the other example above
// if you want the empty "--select--" option
return View();
}
}

Want to demonstrate my object property instead of my object

I have DropDownList that read fils from my database and show this files in my DropDownList.
The current solution is show on my DropDownListItem System.Web.Mvc.SelectList instead of my Object property. I want to include a drop down list of my object (read from database) across my webpage.
This is my object:
public class MyObject
{
public int id { get; set; }
public string fileName { get; set; }
public string browser { get; set; }
public string protocol { get; set; }
public string family { get; set; }
}
My controller:
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
ViewBag.Files = new SelectList(list, "Id", "protocol");
return View();
}
I also try:
List<MyObject> list = db.Captures.Where(x => x.family == "Web")
.DistinctBy(y => y.protocol)
.ToList();
Index.cshtml
#Html.DropDownList("File", new SelectList(ViewBag.Files), "Select webmail site", new { style = "vertical-align:middle;" })
What i want to see in my DropDownList is my protocol property.
All the above not help and all i can see all the time is System.Web.Mvc.SelectList
Change your controller to:
public ActionResult Index()
{
ViewBag.Files = db.MyObjects.Where(x => x.family == "Web").ToList();
return View();
}
and your Index.cshtml
#Html.DropDownList("File", new SelectList(list, "Id", "protocol"), "Select webmail site", new { style = "vertical-align:middle;" })

Categories