Set DropdownList SelectedItem after submit - asp.net

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.

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.

Why Is The Selected Value Different Between Using Route ID and Action Parameter in SelectList

I have a SelectList in my action method. The selected value for SelectList is coming from the action method parameter. The action and view are simple like below:
// Recipe Action
public ActionResult Recipe(int? recipeId)
{
ViewBag.RecipeID = new SelectList(_recipsRecipes, "RecipeID", "RecipeName", recipeId);
return View(new Recipe());
}
//Recipe View
#model RecipeDemo.Models.Recipe
#Html.DropDownList("RecipeID", (SelectList)ViewBag.RecipeID, string.Empty)
I'm using ActionLink below to call the Recipe action.
#Html.ActionLink("Recipe", "Recipe", "Home", new { recipeId = 2 }, null)
It works like I expect, the DropDownList is showing the selected value as the No. 2 (recipeId = 2) item.
Problem
When I change the Recipe action parameter by using route id, like below:
//Recipe View
public ActionResult Recipe(int? id)
{
ViewBag.RecipeID = new SelectList(_recipsRecipes, "RecipeID", "RecipeName", id);
return View(new Recipe());
}
//Recipe View (Same View as above)
#model RecipeDemo.Models.Recipe
#Html.DropDownList("RecipeID", (SelectList)ViewBag.RecipeID, string.Empty)
And I'm using ActionLink below to call the Recipe action.
#Html.ActionLink("Recipe", "Recipe", "Home", new { id = 2 }, null)
The DropDownList is NOT showing the selected value, (id = 2) item. The selection is instead empty.
But I have the correct id value in the SelectList. see below:
Why is this, does anyone know the explanation?
Update:
The model is below:
public class Recipe
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
}
Well that was certainly interesting. After first confirming the issue with the code you provided, I experimented around and believe I have the root cause. Basically, you are using the same variable name way to often and the model binder appears to be getting confused. You have RecipeId in your route, RecipeId in your View Model and RecipeId as the name of your view bag variable. By altering my variable names, the SelectList works as expected.
The primary issue is naming your SelectList RecipeId which matches a property in your model. When you send the new Recipe(), the model binder is attempting to use that value. In your first example, since you have RecipeId defined in the URL, it is getting it from there. In the second example, there is no RecipeId to pull from the URL and it is null in the model.
Controller
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
private List<Recipe> Recipes;
public HomeController()
{
Recipes = new List<Recipe>
{
new Recipe {RecipeId = 1, RecipeName = "Test - 1"},
new Recipe {RecipeId = 2, RecipeName = "Test - 2"},
new Recipe {RecipeId = 3, RecipeName = "Test - 3"},
};
}
public ActionResult Index(int? id)
{
ViewBag.MyList = new SelectList(Recipes, "RecipeID", "RecipeName", id);
return View(new Recipe());
}
}
}
Index View
#model MvcApplication1.Models.Recipe
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DropDownList("MyRecipeId", (SelectList)ViewBag.MyList)
Basically, vary your parameter names a little bit more to help prevent the model binder from getting confused and/or pulling information from the wrong place.
You can verify this in your second example by sending this in your return statement:
Return View(New Recipe{RecipeId = 3});
The option value with 3 will be selected regardless of what the actual Id sent was.
EDIT
An even better option would be to do what I said to do as an example above. By changing your Action to this:
public ActionResult Index(int? id)
{
ViewBag.MyList = new SelectList(Recipes, "RecipeID", "RecipeName");
return View(new Recipe(RecipeId = id));
}
You can leave your view unchanged. Now, the SelectList will pull from the model that you are sending.

mvc3 partial view error

I want to make a form for entering customer data. It consists of several text boxes and a combobox. And it is the whole problem lies in this combobox. When I trying to render this partialview , gets error: "Object reference not set to an instance of an object."
This is partialview controller code
public PartialViewResult GetStates()
{
var states = from s in conn.order_data select s.state;
return PartialView(states.ToList());
}
GetStates partialview
#model IEnumerable<bookstore.state>
#foreach (var item in Model) {
<select>
<option>#item.STATE_Name</option>
</select>
}
part of main view
<div class="editor-field">
#{Html.RenderPartial("GetStates");}
</div>
Please, help
Unless you are loading the view dynamically (in which case you could do it with jquery get)
here is how you could do it
Controller:
public ActionMethod MainView()
{
var model = new myMainModel { States = from s in conn.order_data select s.state };
return View()
}
Main View:
#Html.Partial("MyPartialViewName", Model.States);
Try this:
if(states != null)
{
return PartialView(states.ToList());
}
return PartialView();

Getting values from an asp.net mvc dropdownlist

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.

Resources