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.
Related
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)
New to MVC.
In my page I have several drop down. Currently this is my approach and I feel like repeating myself.
I have created a model, so that I can reuse it for all the dropdown.
public class NameValueModel
{
public int Value { get; set; }
public string Name { get; set; }
}
and then I wrote a data class to fetch value for each dropdown
public IEnumerable<NameValueModel> GetStatus()
{
return (from m in ne.Status
select new NameValueModel { Value = m.StatusID, Name = m.Name }).ToList();
}
public IEnumerable<NameValueModel> GetStates()
{
return (from m in ne.tblStates
select new NameValueModel { Value = m.StateId, Name = m.Name }).ToList();
}
Like wise same code is repeated for each drop down.
Now in my Controller I am calling each of this public method to populate ViewBag
public ActionResult Index(FormCollection f)
{
ViewBag.StateList = new SelectList(new StudentData().GetStates(), "Value", "Name");
ViewBag.ProgramType = new SelectList(new StudentData().GetStatus(), "Value", "Name");
// More of the above
return View();
}
My concern is that I am populating viewBag one by one for each drop down and I have 10 of them, and I am not happy about it.. Is there more sleeker way to get value for all the dropdown as one single call to DB, Cache it, One Model, One call from controller and get all the values for binding.
You can write stored procedure which will return multiple result set and use the DataSet to store the result. Each DropDownList value will be in a saperate table inside the resultant DataSet.
I am a new to ASP.NET MVC, I am developing an application. I want to bind the data in the drop down list in create view.
How to bind the data in the drop down? I have go through many question and answers here...
I have seen usually everyone suggested to use List<SelectListItem> what is its purpose?
Do I need to use ViewModel while binding the data to drop down list?
Can I get simple example where data get bind in the dropdown using viewbag?
I have created a list in controller
List<string> items = new List<string>();
and I want to pass this list to view using viewbag and simply want to bind to drop down list.
How to do this ?
I'd suggest using a ViewModel as it makes interaction with user input so much easier. Here's an example of how you might bind data from your ViewModel to a drop down in your View. First, the ViewModel:
public class CrowdViewModel
{
public string SelectedPerson { get; set;}
public IEnumerable<SelectListItem> People { get; set; }
}
So yes, you're right - use a collection of SelectListItems. I'm guessing in your case, the SelectListItem's Value and Text property will be the same. You could turn your List into IEnumerable like this:
[HttpGet]
public ActionResult Home()
{
// get your list of strings somehow
// ...
var viewModel = new CrowdViewModel
{
People = items.Select(x => new SelectListItem { Text = x, Value = x })
}
return View(viewModel);
}
Now you need to bind that ViewModel's property to the DropDown on your view. If you're using the Razor ViewEngine, the code will look something like this:
#model MyApp.ViewModels.CrowdViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedPerson, Model.People)
}
Now when you post that form, MVC will bind the selected value to the ViewModel's SelectedPerson property!
[HttpPost]
public ActionResult Home(CrowdViewModel viewModel)
{
// viewModel.SelectedPerson == whatever the user selected
// ...
}
Easy as that!
Update:
If you really want to use the ViewBag (don't do it), you can pass your list through from your Controller action like so:
[HttpGet]
public ActionResult Home()
{
ViewBag.People = new List<string> { "Bob", "Harry", "John" };
return View();
}
And then create a SelectList on your View:
#Html.DropDownList("SelectedPerson", new SelectList(ViewBag.People, Model))
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>
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,