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,
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)
I am calling a partial view on which I want to collapse a few dropdown controls(previously created by using DropDownListFor). Because the controls are readonly, I just need to show the selected value on each control. I have created a list called "salutations" in the controller, and pass it as ViewData to my partial view. On the partial view I need to see the selected salutation (e.g.. Mr/Miss/Dr)in my div using #Html.DisplayFor. I tried creating a DisplayTemplate according to an online posting, but I am still having issues getting this to work.
Lookup list declared like this in controller:
var salutations = (IEnumerable<lu_Salutation>)ViewData["salutations"];
Here's my DisplayTemplate named LookupList.cshtml:
#model int
#using System.Linq
#vEmployee.SelectList1.Single(s => s.Value == Model.ToString()).Text
Of course, there's something wrong with the last line of the above code. vEmployee is the name of my model. How do I correct it?, and can I have a generic display template like the GridForeignKey Kendo EditorTemplate so I could easily pass the foreign key, the DisplayTemplate, and the lookup list to get just the text of the selected lookup value displayed?
Ideally, I will just like to have in my partial view, something like:
#Html.DisplayFor(model => model.id, "LookupList", SelectList((IEnumerable)ViewData["salutationList"], "TitleID", "Title"))
where TitleID and Title are respectively the value and text in the lookup list.
Models
public class lu_Salutation
{
public int TitleID { get; set; } // e.g. 1
public string Title { get; set; } // e.g. Mrs
}
ViewModel Class - I want to use just IDs here, but display the matching Texts from the lookup tables (e.g lu_Salutation) when needed
public class vEmployee
{
[Key]
public int EmployeeID { get; set; }
public int SalutationID { get; set; }
}
Controller
[HttpGet]
public ActionResult EmployeeDetails(int employeeID)
{
vEmployee SelectedEmployee = GetEmployees(employeeID).First();
ViewData["salutations"] = _db.lu_Salutation.OrderBy(e => e.Title);
return PartialView("_EmployeeDetails", SelectedEmployee);
}
private IEnumerable<vEmployee>GetEmployees(int employeeID)
{
IEnumerable<vEmployee> emp = (from e in _db.Employees
join c in _db.Contacts on e.EmployeeID equals c.EmployeeID
join u in _db.lu_Salutation on c.SalutationID equals u.TitleID into sal
from u in sal.DefaultIfEmpty()
where (e.EmployeeID == employeeID))
select new vEmployee
{
EmployeeID = e.EmployeeID,
SalutationID = c.SalutationID
}).AsEnumerable().OrderBy(m => m.EmployeeNumber).ThenBy(m => m.FirstName);
return emp;
}
I have a table where I store all the different code/value keywords that I need in my app:
public class Keyword
{
public int id { get; set;}
public string name { get; set; }
public string valuecode { get; set; }
public string valuename { get; set; }
}
Then I use Keyword to store records like these
name valuecode valuename
.DealState 1 Draft
.DealState 2 Final
.DealState 3 Cancelled
.DealType NEW New Business
.DealType RNW Renewal
.DealType WFA Waiting for approval
Then in other models I have fields that are filled using these keywords. For example,
public class Deal
{
....
public string state { get; set; }
public string type { get; set; }
....
}
I have managed to have the fields filled with "valuecode" while displaying "valuename" in Create and Edit views (I use DropDownList with a SelectList built in the controller), but I cannot find a way to display valuename instead of valuecode in Index and Details views.
I'm trying to pass the same SelectList in the ViewBag for Index, but then I do not know which syntax to use in order to replace the "state" code with the state "description" for each record returned.
Any hint?
PS: I'm quite new to .net and mvc, usually work with RoR and ActiveRecord...
EDIT
In my KeywordController I have a method
public SelectList selectKeywordValues(string kwname, object selectedKeyword = null)
{
var keywordsQuery = from d in db.Keywords
where d.name == kwname
orderby d.valuename
select d;
SelectList kwlist = new SelectList(keywordsQuery, "valuecode", "valuename", selectedKeyword);
return kwlist;
}
Then in my DealController i have the index method
public ActionResult Index()
{
var kw = new KeywordController();
ViewBag.state = kw.selectKeywordValues(".DealState");
return View(db.Deals.ToList());
}
SOLVED
In DealController the index method is the following
public ActionResult Index()
{
var kw = new KeywordController();
SelectList states = kw.selectKeywordValues(".DealState");
SelectList types = kw.selectKeywordValues(".DealType");
foreach (var item in db.Deals.ToList())
{
SelectListItem mystate = states.Where(row => row.Value == item.state).ElementAt(0);
SelectListItem mytype = types.Where(row => row.Value == item.type).ElementAt(0);
item.state = mystate.Text;
item.type = mytype.Text;
}
return View(db.Deals.ToList());
}
Now the db.Deals.ToList() is filled with descriptions and not with codes.
You can define a view model called DealViewModel that contains DealState and DealType properties. Then populate the DealViewModel with joins in LINQ before passing to the views that reference the view model.
Another approach is to use enums in EF5.
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.
Not sure if i'm populating my dropdown correctly but I'm having issue validating the values in my dropdownlist. When a value has been selected it's still showing error 'The value x is invalid'. The type is of int? as I know int doesn't work with the validator.
View model code:
[Display(Name = "Category")]
[Required(ErrorMessage = "Category is required.")]
public AWS.DTO.Lookup Category { get; set; }
public IEnumerable<AWS.DTO.Lookup> Categories { get; set; }
Controller code:
[PageOptions(Title = "Create FMR")]
public ActionResult Create()
{
var model = new FMRRequestViewModel();
model.Categories = new AWS.BL.Lookup().GetFMRCategories();
return View(model);
}
Lookup Type:
public class Lookup
{
public int? ID { get; set; }
public string Description { get; set; }
}
View code:
#Html.DropDownListFor(m => m.Category, new SelectList(Model.Categories, "ID", "Description", -1), "-- Please Select -- ")
Thanks in advance for any help.
DropDown's don't work that way. A dropdown can only send the ID, not the text. You are passing the whole Category object to DropDownListFor, which it won't understand.
#Html.DropDownListFor(m => m.Category.ID, new SelectList(Model.Categories, "ID", "Description", -1), "-- Please Select -- ")
It's not going to bind to a Lookup model once selected. MVC doesn't work like ASP where you receive back an object (ASP you'd "bind" an enumerable of objects and, when selected, the whole object was returned--this is not the case in mvc, only the key will be returned (or whatever property was mapped as the dropdown's value)).
Instead you'd have to accept an Int32 then in your action retrieve the matching Lookup. So, in short:
change your ViewModel so Category is an Int32/int (and not a Lookup object).
in the receiving action map the Lookup based on what Category has for a populated value.