Bootstrap Multiselect Get Selected values on HttpPost - asp.net-mvc

I'm using this Bootstrap Multiselect and my problem is that I cant get the selected values on HttpPost on ASP.Net MVC.
Problems Encountered:
after clicking save, Only the first selected value is the present on
the model. (SOLVED)
after clicking save, Only the first selected value is the present on
the dropdownlist.
Sample.chtml:
#model SampleProject.Models.SampleViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.Selected, new SelectList(Model.List, "value", "text"), new { #class = "multiselect form-control", multiple = "multiple" })
<input type="submit" value="Save" />
}
Model:
public class SampleViewModel
{
public string[] Selected { get; set; }
public SelectList List { get; set; }
}
Controller:
public class DashboardController : Controller
{
public ActionResult Sample()
{
SampleViewModel model = new SampleViewModel();
model.List = new SelectList(new List<string>() { "1", "2", "3" });
return View(model);
}
[HttpPost]
public ActionResult Sample(SampleViewModel model)
{
model.List = new SelectList(new List<string>() { "1", "2", "3" });
return View(model);
}
}
Selection:
I cant get the selected values correctly on HttpPost
Code Behind/HttpPost: (Wrong)
After HttpPost: (Correct)

A <select multiple="multiple"> posts back an array of values (not a single value). You property Selected needs to be IEnumerable, for example
public string[] Selected { get; set; }
Side note: Since the text and value properties are the same, you can simplify you code by making the List property SelectList
public SelectList List { get; set; }
and then in the controller
model.List = new SelectList(new List<string>() { "1", "2", "3" })
(although its not clear why you would not use int)

Didn't see this answer anywhere, so to solve the issue with having only 1 item selected after the post back you need to use:
#Html.ListBoxFor(..
instead of #Html.DropDownListFor

Related

Unable to set value in dropdownlist

I have a dropdownlist,while editing i need to set the current value.But my codes are not working.
My view look like follow
#Html.DropDownListFor(m => m.id, Model.ddls, "Please Select", new { #class = "form-control" })
Model
public string id { get; set; }
public List<SelectListItem> ddls { get; set; }
Controller
public IActionResult editmaster(string id, string sec)
{
master m = new master();//here is my model
m.ddls = PopulateDDLDataSet(ds.Tables[1], "companyname", "companyid");//ddls is my object and populateddldataset is my methode to fill the list
return View(m);
}
ddls is the selectedlistitems that i have filled from controller,that work fine.But the value which in in id not set on the list
Checked the code and its working for me. Could you provide more details about your model?
Wanted to say that you can make similar things by using built-in razor tag helpers that is more clear.
Documentation for select
Example of using tag helper in your code:
<select class="form-control" asp-for="#Model.id" asp-items="Model.ddls">
<option selected>Please select</option>
</select>
please follow this, it may be this code help you.
Model Code
public class testmdl
{
public string id { get; set; }
public IEnumerable<SelectListItem> ddls { get; set; }
}
Controller Code
//------ without using entity for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
IEnumerable<SelectListItem> companyList = new List<SelectListItem>
{
new SelectListItem { Value = "001", Text = "StackOverflow1" },
new SelectListItem { Value = "002", Text = "StackOverflow2" }
};
obj.ddls =companyList ;
return View(obj);
}
//--- using entity framework for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
List<SelectListItem> companyList = new SelectList(db.yourcompanytable, "companyid", "comapnyname").ToList();
obj.ddls =companyList ;
return View(obj);
}
View Code
<select id="id1" name="id1" asp-for="id" asp-items="#Model.ddls" class="form-control">
<option value=#null>--- Select --- </option>
</select>
<span asp-validation-for="id" style="color:red;"></span>
In my case none of the above answers work(I don't clearly understand what went wrong for me) ,but finally i achieved in an alternative way.Below my codes.Thanks for all the supports.
<script>
document.getElementById("id").value =#Model.id;
</script>
Put this after binding the dropdownlist.

Html.DropDownListFor returns null

There are similar questions and I have tried most of them. Instead of continuing to destroy the remaining code while conjuring demons from the similar past questions, I have decided to ask for help.
When I arrive at the AddMembership action I get a null value instead of the selected item. Below are the details.
View;
#using (Html.BeginForm("AddMembership", "WorkSpace", FormMethod.Post, new { data_ajax = "true", id = "frmAddMembership" }))
{
<div id="newMembershipDiv">
#Html.DropDownListFor(m => m.selectedID, new SelectList(Model.allInfo, "Value","Text",1), "Select!")
<input type="submit" value="Add" name="Command" />
</div>
}
Controller (I just want to see the selectedID or anything appear here.);
public ActionResult AddMembership(SelectListItem selectedID)
{
return View();
}
Model;
public class SomeModel
{
public SelectList allInfo { get; set; }
public SelectListItem selectedID { get; set; }
}
The Monstrosity which initializes the allInfo SelectList
model.allInfo = new SelectList(synHelper.getall().ToArray<Person>().Select(r => new SelectListItem {Text=r.Name, Value=r.prID.ToString() }));
synHelper.getAll() returns a List of the below class;
public class Person
{
public Guid prID { get; set; }
public string Name { get; set; }
}
The only thing that is posted to your action is a selectedID, which is a simple string. If you wander, in the request it looks as simple as:
selectedID=1234
Therefore it should be awaited for as a simple string. Adjust your action parameter:
public ActionResult AddMembership(string selectedID)

SelectList selected value not carried over to DropDownList

I have a Razor page with a drop down list inside a form:
#using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { #id = "ProductsByOwners" }))
{
#Html.Label("Choose product owner: ")
#Html.DropDownList("OwnerList", (SelectList)ViewBag.OwnerList, new { #onchange = "this.form.submit();" })
}
The selected value of my SelectList is not being carried over to the DropDownList. I've debugged and stepped through the code and found that (SelectList)ViewBag.OwnerList evaluates properly and has the expected value selected, but the resulting HTML does not have any of the option tags selected.
Can anyone see what I'm doing wrong here?
UPDATED
Here is how the SelectList is created in my action:
ViewBag.OwnerList = new SelectList(ListUtils.ProductOwners(), "Key", "Value", values["OwnerList"]);
The result has the value indicated by values["OwnerList"] selected.
Thanks!
You are not using the DropDownList helper properly. In order to create a dropdownlist you need 2 things:
a scalar property to bind to the selected value when the form is submitted
a collection to bind the options to
In your example you have only one of those 2 things (the second). Your first argument is called OwnerList and you have ViewBag.OwnerList passed as second argument.
So:
#Html.DropDownList(
"SelectedOwnerId",
(SelectList)ViewBag.OwnerList,
new { #onchange = "this.form.submit();" }
)
Obviously I would recommend you using strongly typed views ans view models. And obviously get rid of the weakly typed ViewBag/ViewData/ViewCrap.
So start by designing a view model to meet the requirements of your view (which from what you have shown so far is to display a dropdownlist):
public class OwnerViewModel
{
[DisplayName("Choose product owner: ")]
public string SelectedOwnerId { get; set; }
public IEnumerable<SelectListItem> OwnerList { get; set; }
}
then a controller:
public class ReportController: Controller
{
public ActionResult ProductsByOwners()
{
var model = new OwnerViewModel
{
// preselect the second owner
SelectedOwnerId = "2",
// obviously those come from your database or something
OwnerList = new[]
{
new SelectListItem { Value = "1", Text = "owner 1" },
new SelectListItem { Value = "2", Text = "owner 2" },
new SelectListItem { Value = "3", Text = "owner 3" },
}
};
return View(model);
}
[HttpPost]
public ActionResult ProductsByOwners(OwnerViewModel model)
{
...
}
}
and you have a corresponding strongly typed view:
#model OwnerViewModel
#using (Html.BeginForm("ProductsByOwners", "Report", FormMethod.Post, new { id = "ProductsByOwners" }))
{
#Html.LabelFor(x => x.SelectedOwnerId)
#Html.DropDownListFor(
x => x.SelectedOwnerId,
Model.OwnerList,
new { onchange = "this.form.submit();" }
)
}
The most common reason the selected item is not selected in the DDL is you've named the selectlist the same as the model.
Strongly typed views are preferred, but it's fine to pass the SelectList in a Viewbag. See my tutorial Working with the DropDownList Box and jQuery and my blog Cascading DropDownList in ASP.Net MVC

Set HTML dropdownlist selected item using value from ViewModel

I have an HTML dropdown list:
<select name="status">
<option value="close" >Close Task</option>
<option value="open" >Reopen Task</option>
</select>
I want to set the 'selected' option based on the 'Task.Completion' property in my view model:
public class TaskEditViewModel
{
public Task Task { get; set; }
public TaskComment TaskComment { get; set; }
}
So if Task.Completion is NULL, the 'close' option is selected, otherwise the 'open' option is selected.
How can I do this?
Your view model doesn't seem adapted to what you are trying to do in the view (which according to your question is show a dropdown list and preselect a value based on some property on your view model).
So a far more realistic view model would be this:
public class TaskEditViewModel
{
public string Completion { get; set; }
public IEnumerable<SelectListItem> Actions
{
get
{
return new[]
{
new SelectListItem { Value = "close", Text = "Close Task" },
new SelectListItem { Value = "open", Text = "Reopen Task" },
};
}
}
}
then you could have a controller action which will populate and pass this view model to the view:
public ActionResult Foo()
{
var model = new TaskEditViewModel();
// this will automatically preselect the second item in the list
model.Completion = "open";
return View(model);
}
and finally inside your strongly typed view you could use the DropDownListFor helper to render this dropdown:
#model TaskEditViewModel
#Html.DropDownListFor(x => x.Completion, Model.Actions)

How does Model binding with a selectlist work?

I'm having problems retrieving the values of a selectlist in my form collection. I've tried making a viewmodel with an attribute with the same name as the select list.
I'm honestly just realizing I REALLY don't understand how model binding works with selectlists. I've just been assuming that the following conventions apply:
Name the select list the same thing as the attribute on the model you want it to bind to.
Apart from that, I really don't get it. I've looked at several books on it and they're useless frankly.
How does a select list work with a) form collection and b) a particular model?
Here's an example:
Model:
public class MyViewModel
{
public string SelectedItemValue { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch those from a repository
Items = new SelectList(
new[]
{
new SelectListItem { Value = "1", Text = "Item 1" },
new SelectListItem { Value = "2", Text = "Item 2" },
new SelectListItem { Value = "3", Text = "Item 3" },
},
"Value",
"Text"
)
};
}
[HttpPost]
public ActionResult Index(string selectedItemValue)
{
// Here you get the selected value from the dropdown
return ...
}
}
View:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedItemValue, Model.Items)
<input type="submit" value="OK" />
<% } %>

Resources