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"))
Related
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)
...
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();
}
}
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;" })
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)
I am trying to build a Dropdownlist, but battling with the Html.DropDownList rendering.
I have a class:
public class AccountTransactionView
{
public IEnumerable<SelectListItem> Accounts { get; set; }
public int SelectedAccountId { get; set; }
}
That is basically my view model for now. The list of Accounts, and a property for returning the selected item.
In my controller, I get the data ready like this:
public ActionResult AccountTransaction(AccountTransactionView model)
{
List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);
AccountTransactionView v = new AccountTransactionView
{
Accounts = (from a in accounts
select new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString(),
Selected = false
}),
};
return View(model);
}
Now the problem:
I am then trying to build the Drop down in my view:
<%=Html.DropDownList("SelectedAccountId", Model.Accounts) %>
I am getting the following error:
The ViewData item that has the key 'SelectedAccountId' is of type 'System.Int32' but must be of type 'IEnumerable'.
Why would it want me to return the whole list of items? I just want the selected value. How should I be doing this?
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
#model MvcVariousApplication.Models.RechargeMobileViewModel
#{
ViewBag.Title = "Contact";
}
#Html.LabelFor(model=> model.CustomerFullName)
#Html.TextBoxFor(model => model.CustomerFullName)
#Html.LabelFor(model => model.MobileNumber)
#Html.TextBoxFor(model => model.MobileNumber)
#Html.LabelFor(model => model.TelecomSubscriber)
#Html.TextBoxFor(model => model.TelecomSubscriber)
#Html.LabelFor(model => model.TotalAmount)
#Html.TextBoxFor(model => model.TotalAmount)
#Html.LabelFor(model => model.Month)
#Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")