Getting values from an asp.net mvc dropdownlist - asp.net

Can someone help me with getting values from a dropdownlist in asp.net mvc?
I can get values from textboxes,etc...but,how do I get these 2 things...
Getting Selected Item Value of the drop down list from the controller class
Getting all the list of items of the drop down list from the controller class
Thanks

You can get the selected value from a drop down list the same way as you do for text boxes.
Using default model binding
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
//MyList will contain the selected value
//...
}
or from a FormCollection
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(FormCollection form) {
string val = form["MyList"];
//...
}
or from the request
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
string val = Request.Form["MyList"]; //or
val = Request["MyList"];
//...
}
Where your drop down list is named "MyList".
<%= Html.DropDownList("MyList", MyItems) %>
or straight HTML
<select name="MyList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
The browser will only submit the selected value from the drop down list and not all the other values. To get the list of all the other items you should invoke the code that populated the list in the first place (assuming you used Html.DropDownList()).
Update
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample() {
ViewData["MyItems"] = GetSelectList();
return View();
}
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample(string MyList) {
//MyList contains the selected value
SelectList list = GetSelectList(); //list will contain the original list of items
//...
}
private SelectList GetSelectList() {
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("Item 1", "1");
list.Add("Item 2", "2");
list.Add("Item 3", "3");
return new SelectList(list, "value", "key");
}
//...
<%= Html.DropDownList("MyList", ViewData["MyItems"] as SelectList) %>

Well it's hard to answer correctly since you've given so little information, but in general you get the selected value in the post method of the Controller.
Something like this might explain it better:
Consider having this dropdownlist:
//instantiate the dropdownlist in the controller method.
public ActionResult Create() {
List<string> items = new List<string>() {"first", "second", "third"};
SelectList SomeSelectItems = new SelectList(items);
ViewData["list"] = SomeSelectItems;
return View();
}
<%= Html.DropDownList("DDL", (SelectList)ViewData["list"]) %>
In your controller you would get the value of the dropdownlist like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string DDL)
{
string theValue = DDL;
return View();
}
To get all the values from the dropdownlist would be the same as putting them into the selectlist in the first place. I will assume you have a method that is called to fill the dropdownlist with items. Simply call this method from within the controller and handle the values appropriately.

I think you need to rethink this. The values for the dropdown should come from the controller and sent to the view for display in the dropdown to allow the user to select. Then the page form sends the selected value back to the controller. Data should always be on the server side and the view is just for display.

Related

Attempting to return view model of SelectListItem dropdown [duplicate]

This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 4 years ago.
Here is my controller
[HttpGet]
public IActionResult Unregister(LinkedServiceTable lst)
{
lst.BuildLinkedServices();
var model = new LinkedServiceTableViewModel
{
LinkedServices = GetLinkedServices(lst)
};
return View(model);
}
[HttpPost]
public IActionResult Unregister(LinkedServiceTableViewModel vm)
{
return View(vm);
}
private IEnumerable<SelectListItem> GetLinkedServices(LinkedServiceTable lst)
{
var roles = lst.LinkedServices.Select(x => new SelectListItem
{
Value = x.LinkedServiceId.ToString(),
Text = x.ServiceName
});
return new SelectList(roles, "Value", "Text");
}
Here is my razor view
#model CDIWeb.ViewModels.LinkedServiceTableViewModel
#{
ViewData["Title"] = "Unregister Linked Service";
}
<h2>#ViewData["Title"]</h2>
<form action="/LinkedService/Unregister" method="post">
#Html.LabelFor(m => m.SelectedLinkedServiceId)
#Html.DropDownListFor(m => m.SelectedLinkedServiceId, Model.LinkedServices)
<button type="submit" value="Submit">Submit</button>
</form>
All I want to do is submit myrazor view, then redirect back to the same page with the submited option on the dropdown selected. However, I am getting this error on HttpPost view, the HttpGet view is working fine and I am able to submit successfully.
InvalidOperationException: The ViewData item that has the key 'SelectedLinkedServiceId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
Any ideas on why this is happening and how to fix it?
The problem is you will need to fill the DropDownList with data again, because those data doesn't persist between postbacks.
[HttpPost]
public IActionResult Unregister(LinkedServiceTableViewModel lst)
{
// Do something, and display the page again with data.
lst.BuildLinkedServices();
lst.LinkedServices = GetLinkedServices(lst);
return View(lst);
}
I solved this in the past by doing the following.
Create an IEnumerable:
#{
ViewData["Title"] = "Unregister Linked Service";
IEnumerable<SelectListItem> selectList =
from cf in Model.LinkedServices
select new SelectListItem
{
Selected = cf."your value",
Text = cf."your value",
Value = cf."your value"
};
}
Then after you create the IEnumerable list, just use it in your razor:
#Html.DropDownListFor(m => m.SelectedLinkedServiceId, selectList)

DropDownList SelectedItem Not Working (Razor ASP MVC5)

Model
public class MyModel {
public string ItemXYZ { get; set; }
}
Controller
public ActionResult Edit(int? id)
{
var x = db.XYZs.Find(id);
ViewBag.Item_XYZ = new SelectList(new[] { "X", "Y", "Z"}, x.CurrentXYZ);
}
View
#Html.DropDownList("XYZ123", #ViewBag.Item_XYZ as SelectList, new { #class = "special-class" })
Problem
If I change my DropDownList to mach the name of the get set in my model, the selected value does not work.
#Html.DropDownList("ItemXYZ" ....)
If it matches the name of my ViewBag item, the SelectedItem doesn't work.
#Html.DropDownList("Item_XYZ" ....)
But, if I append 123 (for example), SelectedItem works just fine.
UPDATE
This is the same issue I am having, but I don't understand why or how to handle the return in my controller?
In Controller use the code as::
public ActionResult Edit(int? id)
{
var x = db.XYZs.ToList();
ViewBag.TestDropdown = new SelectList(x, "ValueField", "TextField", "DefaultSelected");
}
and in Client side to show Dropdown use this:
#Html.DropDownList("TestDropdown")
thats it.
May be this will help you.
Receive a parameter named XYZ123 in respective action.
Also include XYZ123 in Bind attribute of action.

How to set the .Selected property of an item in ASP.NET MVC SelectList using LINQ?

I am trying to populate a SelectList in an action method for a dropdown list in the view. The dropdown gets displayed on the view just fine but the selected attribute doesn't show up using the following code:
public ActionResult Edit(int ID)
{
var ctx = new NorthwindEntities();
var product = ctx.Products.Where(p => p.ProductID == ID).SingleOrDefault();
var selectList = new SelectList(ctx.Categories, "CategoryID", "CategoryName");
selectList.Where(s => s.Value == product.CategoryID.ToString()).SingleOrDefault().Selected = true;
ViewData["CategoryID"] = selectList;
return View(product);
}
However, passing the selectedValue parameter to SelectList constructor does the job:
var selectList = new SelectList(ctx.Categories, "CategoryID", "CategoryName", product.CategoryID.ToString());
My guess is that Either the LINQ expession is the problem or SelectedItem can only be specified in the SelectList constructor. Any ideas?
This question is answered here
Set selected value in SelectList after instantiation
If you still think it is wrong then break your linq query up and check to see if you can find an object in the list, and then do an if( obj != null) { selected = true;}
But from what I have read the selected property can only be set in the constructor.
in that link is a wrapper/helper method
public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue)
{
return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue));
}
That migth help you

Set DropdownList SelectedItem after submit

I have a dropdownlist is set to '--Select Item--' when the form is loaded first time. I don't see the Selected Item getting selected after I submit the form. It is set to '--Selected Item--' again. What could be the problem?
<%= Html.DropDownList("lstDetails", new SelectList((IEnumerable)ViewData["DetailList"], "ID", "Details"), "--Select Item--")%>
Thanks..
I assume you wish to save the selected item somewhere.
<%: Html.DropDownFor(selectedId, new SelectList((IEnumerable)ViewData["DetailList"], "ID", "Details", (IEnumerable)ViewData["DetailList"].FirstOrDefulft(x => x.Id == selectedId), "--SelectItem--") %>
You need to store the information which item was selected. I used here an int called
int selectedId
I assumed you have a Id field in your detailList items.
The easiest way is to put SelectList in the model. (Just make sure you are creating the SelectList in the constructor of the model).
View:
<%= Html.DropDownList("lstDetails", Model.DetailList)%>
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyController(MyModel model)
{
return View(model);
}
Model:
class MyModel
{
public SelectList DetailList;
public MyModel()
{
DetailList = new SelectList(....
}
}
So after you post back, if you return the view with the same model then the form will look the same as before you submitted the form.

ASP MVC Dropdown

Please look at my code. I am trying to display some dynamic customers in the dropdown menu. And after selecting a customer button is pressed. Then products owned by the selected customer should be displayed in the textarea. But the problem is that after selecting a customer and pressing the button, nothing is displayed in the text area !. As i am new to ASP MVC can you help me out this problem?
Controller class-------------------->
public class ProductsController : Controller
{
CandidateEntities db;
public ProductsController()
{
db = new CandidateEntities();
}
public ActionResult Index()
{
ViewData["Customers"] = new SelectList(db.Customer.ToList(), "CustomerId", "Firstname");
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
int customerId = int.Parse(form["Customers"]);
var cust = db.Customer.First(x=>x.CustomerId == customerId);
var Query =
from customer in db.Customer
join prod in db.Products on customerId equals prod.Customer.CustomerId
select prod;
ViewData["Products"] = Query.ToString();
return View("Index");
}
}
Index view------------------>
Index
<%using(Html.BeginForm()){ %>
<%=Html.DropDownList("Customers", "Seletc one")%>
<input type="submit" value="Click !" />
<%=Html.TextArea("Textarea", ViewData["Products"]) %>
<%} %>
Are you sure your query is returning results? It seems to be querying for every product for every customer, it might be rewritten something like:
from product in db.Prodcuts
where product.Customer.CustomerID = customerId
select product
Also, (and it depends on your code), but is calling ToString on a list of Product objects going to return what you want?
db.Products.Where(p => p.CustomerId == cust)
or
db.Customer.Find(cust).Products

Resources