Show dropdownlist in the View - asp.net-mvc

I am working on a project in which, i am getting the client names from database table using the HomeController>Index Action method.
I want to send this list to Index view and display this list in the dropdownlist.
Request you to please help me with the View accordingly as i am new to MVC.
Home Controller
public ActionResult Index()
{
var model = from c in
_mdlCntxtcls.clients
where (DateTime.Now<=c.End_Date)
select c;
return View(model);
}
Model
public class Client
{
public int ClientID { get; set; }
public string Client_Names { get; set; }
public DateTime Start_Date { get; set; }
public DateTime End_Date { get; set; }
}
Please help as early as possible
Thank you

You are passing a collection of Client objects to the view. So your view should be strongly typed to a collection of Client object to accept that as the (view) model data.
You can use the DropDownList html helper method to render a SELECT element from this view model data. You can create a SelectList object from this collection (your page model)
#model IEnumerable<YourNamespaceHere.Client>
#Html.DropDownList("StudentSelect",new SelectList(Model,"ClientID","Client_Names"))
This will render a SELECT element with name attribute value set to StudentSelect. Each options in the SELECT elemtn will have the ClientID as the value attribute value and Client_Names property value as the option text.

You can also use viewbag or viewdata for send list of Client from controller to view and then you can put it in dropdown list.
In Controller you can use like :
List<SelectListItem> ClientList = new List<SelectListItem>();
using (dbContext db = new dbContext())
{
var Clients = db.Client.ToList();
foreach (var i in Clients)
{
ClientList.Add(new SelectListItem { Text = i.Client_Name, Value = i.ClientID.ToString() });
}
}
ViewBag.ClientList = ClientList;
and in view side you can use that viewbag like :
#Html.DropDownListFor(x => x.Client, (IEnumerable<SelectListItem>)ViewBag.ClistList)

Related

Multiple Dropdown Lists, Multiple Models

I have a few entities that I want to fill into a few dropdown lists on a single form. Which is the best way to go about doing so. For multiple models in a single view I've created a viewmodel and threw the entities into it but how can I bring back the list in the database say for entity "Network" and fill the dropdown with "Name" and "NetworkID"?
First create the Model:
public class Data
{
public List<tbl_Dept> lstDepatrment;
public List<tbl_employees> lstEmployee;
//other
}
Then just Create a View
#model MVCApp.Models.Data
#{
var categoryList = Model.lstDepatrment.Select(cl => new SelectListItem
{
Value = cl.Dept_ID.ToString(),
Text = cl.Dept_Description == null ? String.Empty : cl.Dept_Description
});
//list for other Drop Down
}
#(Html.DropDownList("sampleDropdown", categoryList, "-----Select-----"))
You can do as follows:
Designing your model:
Prepare Select List for as many dropdowns you want
For eg:
Public class ModelName
{
...// Properties
public IEnumerable<SelectListItem> ListName1 { get; set; }
public IEnumerable<SelectListItem> ListName2 { get; set; }
public IEnumerable<SelectListItem> NetWorkList { get; set; }
... //etc
}
Prepare and bind List to Model in Controller :
public ActionResult Index(ModelName model)
{
var networks = // Your network List
model.NetWorkList = networks.Select(x=> new SelectListItem() {
Text = x.Name,
Value = x.NetworkID
});
..// Same as above prepare the list for other dropdowns
return View(model);
}
Then in your view prepare your dropdown as follows:
#Html.DropDownListFor(m => Model.NetworkID,Model.NetWorkList)
Well in that case you can keep all the model list data in somewhere in java script model and then using the JQuery you can bind all of Dropdown controls with same model list.
Alternatively you can fetch that data using Ajax and bind those Dropdowns there in java script and retrieve the value rather then throwing data multiple list from controller.

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Int32]'

ASP.Net MVC 4
I am trying to populate a list of Countries (data from Country table in DB) in a dropdownlist. I get the following error:
The model item passed into the dictionary is of type
System.Collections.Generic.List`1[System.Int32]', but this dictionary requires a model item of type 'BIReport.Models.Country'.
I am new to ASP.Net MVC and I don't understand that error. What I feel is what Index method is returning doesn't match with the model that I am using in the View.
Model::
namespace BIReport.Models
{
public partial class Country
{
public int Country_ID { get; set; }
public string Country_Name { get; set; }
public string Country_Code { get; set; }
public string Country_Acronym { get; set; }
}
}
Controller::
public class HomeController : Controller
{
private CorpCostEntities _context;
public HomeController()
{
_context = new CorpCostEntities();
}
//
// GET: /Home/
public ActionResult Index()
{
var countries = _context.Countries.Select(arg => arg.Country_ID).ToList();
ViewData["Country_ID"] = new SelectList(countries);
return View(countries);
}
}
View::
#model BIReport.Models.Country
<label>
Country #Html.DropDownListFor(model => model.Country_ID, ViewData["Country_ID"] as SelectList)
</label>
Where am I going wrong?
You are selecting CountryIDs, therefore you will have a list of integers passed into the view.
I think you really want something like this:
public ActionResult Index()
{
var countries = _context.Countries.ToList();
ViewData["Country_ID"] = new SelectList(countries, "Country_ID", "Country_Name");
return View();
}
I'm not really sure why you have single country as a model for your view.
Update:
I'm still not sure why the model is a country, if you are just going to post the ID of the selected country you don't necessarily need a model at all (or just have an integer). This will be just fine though:
View
#model MvcApplication1.Models.Country
#Html.DropDownListFor(m => m.Country_ID, ViewData["Country_ID"] as SelectList)
the problem is in line 1 of your view. change it like this :
#model IEnumerable<BIReport.Models.Country>
also there is no need to pass the model to view if you already did it by :
ViewData["Country_ID"] = new SelectList(countries);
When you say #model BIReport.Models.Country it means your view is expecting a model consisting single country details. On the contrary you need a list of countries to be displayed in the drop-down list. Hence you should tell the view to look for a list of country details instead.
Therefore #model IEnumerable.

How do I add a Custom Query for a drop down and retain the View Model Pattern?

I've read many articles which they state that querying should not be placed in the Controller, but I can't seem to see where else I would place it.
My Current Code:
public class AddUserViewModel
{
public UserRoleType UserRoleType { get; set; }
public IEnumerable<SelectListItem> UserRoleTypes { get; set; }
}
public ActionResult AddUser()
{
AddUserViewModel model = new AddUserViewModel()
{
UserRoleTypes = db.UserRoleTypes.Select(userRoleType => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)userRoleType.UserRoleTypeID).Trim(),
Text = userRoleType.UserRoleTypeName
})
};
return View(model);
}
The View:
<li>#Html.Label("User Role")#Html.DropDownListFor(x => Model.UserRoleType.UserRoleTypeID, Model.UserRoleTypes)</li>
How do I retain the View Model and Query and exclude the User Type that should not show up?
I think that you are doing it just fine.
Any way... all you can do to remove the querying logic from controller is having a ServiceLayer where you do the query and return the result.
The MVC pattern here is used correctly... what your are lacking is the other 2 layers (BusinessLayer and DataAccessLayer)... since ASP.NET MVC is the UI Layer.
UPDATE, due to comment:
Using var userroletypes = db.UserRoleTypes.Where(u=> u.UserRoleType != 1);
is OK, it will return a list of UserRoleType that satisfy the query.
Then, just create a new SelectList object using the userroletypes collection... and asign it to the corresponding viewmodel property. Then pass that ViewModel to the View.
BTW, I never used the db.XXXX.Select() method before, not really sure what it does... I always use Where clause.
SECOND UPDATE:
A DropDownList is loaded from a SelectList that is a collection of SelectItems.
So you need to convert the collection resulting of your query to a SelectList object.
var userroletypes = new SelectList(db.UserRoleTypes.Where(u=> u.UserRoleType != 1), "idRoleType", "Name");
then you create your ViewModel
var addUserVM = new AddUserViewModel();
addUserVM.UserRoleTypes = userroletypes;
and pass addUserVM to your view:
return View(addUserVM );
Note: I'm assuming your ViewModel has a property of type SelectList... but yours is public IEnumerable<SelectListItem> UserRoleTypes { get; set; } so you could change it or adapt my answer.
I don't see anything wrong with your code other than this db instance that I suppose is some concrete EF context that you have hardcoded in the controller making it impossible to unit test in isolation. Your controller action does exactly what a common GET controller action does:
query the DAL to fetch a domain model
map the domain model to a view model
pass the view model to the view
A further improvement would be to get rid of the UserRoleType domain model type from your view model making it a real view model:
public class AddUserViewModel
{
[DisplayName("User Role")]
public string UserRoleTypeId { get; set; }
public IEnumerable<SelectListItem> UserRoleTypes { get; set; }
}
and then:
public ActionResult AddUser()
{
var model = new AddUserViewModel()
{
UserRoleTypes = db.UserRoleTypes.Select(userRoleType => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)userRoleType.UserRoleTypeID).Trim(),
Text = userRoleType.UserRoleTypeName
})
};
return View(model);
}
and in the view:
#model AddUserViewModel
<li>
#Html.LabelFor(x => x.UserRoleTypeId)
#Html.DropDownListFor(x => x.UserRoleTypeId, Model.UserRoleTypes)
</li>

DropDownListFor() bindling value AND text to viewmodel

I have a form on a View with a dropdown list, implemented with DropDownListFor(). This View is strongly typed to a ViewModel, which has a SelectList property to hold the options of the dropdown, and then another property to hold the selected value of the dropdown. This is working fine, but what I'd like to do is, hold both the selected value AND selected text of the dropdown in my second property. The reason I want to do this is so that as the form selfposts, I have both the text and value of each selection.
I tried changing the selected value property from an int to a KeyValuePair but only the int part of the pair is set on form submission.
Perhaps there is a better way altogether to accomplish this, I am open to all suggestions including a partial redesign of my methods.
Controller (building SelectList)
SelectList leadTypeGroups = new SelectList(_enrollmentRepository.GetLeadTypeGroups(), "Key", "Value");
ViewModel
public KeyValuePair<int, string> LeadTypeGroupID { get; set; }
public SelectList LeadTypeGroups { get; set; }
View
#Html.DropDownListFor(selected => Model.LeadTypeGroupID, Model.LeadTypeGroups, " ")
Have the sever pull the values from the database (or an in-memory cache) on each request. Alternatively, have a hidden field with javascript that updates it with the appropriate text whenever the dropdown selection changes.
Change the ViewModel to a List and then use a for loop to spit out a drop down for each item in the list. Something like...
View
#for( int i = 0; i < Model.LeadTypeGroupIDs; i++ )
{
#Html.DropDownListFor(x => Model.LeadTypeGroupIDs[i], Model.LeadTypeGroups, " ")
}
ViewModel
public List<string> LeadTypeGroupIDs { get; set; }
public SelectList LeadTypeGroups { get; set; }

Populate a dropdown list from db

I have an mvc 3 application with 2 tables in my entity framework.
PurchaseTable which was PurchaseID,PurchaseDate & ProductID I have another table called Product which contains ProductID and ProductName. creating a new view to insert a new purchase how do I change the textbox in the view for ProductID to be a dropdown bound by the ProductName in the Product table?
Create a ViewModel:
public class CreatePurchaseViewModel
{
public Purchase Purchase { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
public int SelectedProductId { get; set; }
}
Setup the View with the ViewModel:
[HttpGet]
public ActionResult CreateProduct()
{
var model = new CreatePurchaseViewModel
{
Products = repository.FindAllProducts().Select(x =>
new SelectListItem
{
Text = x.ProductName,
Value = x.ProductId
}
};
return View(model);
}
Then simply bind to the ViewModel and use the DropDownListFor HTML Helper:
<! -- other code to bind to Purchase, and then: -->
<%= Html.DropDownListFor(x => x.SelectedProductId, Model.Products) %>
Then when you submit the form, the SelectedProductId value in the model will be populated with the selected value from the dropdown list.
The answer is easier than it looks. Simply create a list:
myDropDown = new SelectList(db.Products, "Product_ID", "ProductName", idSelected);
The first parameter is your table ("Products" from the Entity Model), the second is the "id" that will be returned when selecting from the list (i.e SelectedValue), the third is the "text" that will be displayed in the list and the last parameter is the currently selected item.
Assuming your model is called MyTablesDB, then:
MyTablesDB db = new MyTablesDB();
For example:
public SelectList GetPullDown(object idSelected) {
myTablesDB myDB = new MyTablesDB();
return new SelectList(myDB.Products, "Product_ID", "Product_Name", idSelected);
}
Cheers,

Resources