I use JavaScript for populating a list called "groups".
Then I create a DropDownList:
<div class="form-group">
<div class="col-md-10">
#Html.DropDownList("groups", new SelectList(string.Empty, "Value", "Text"), "Choose...")
</div>
</div>
The DropDownList displays fine.
What I need to do is assign the chosen value from "groups" to the model.group_id.
I don't know how to get the item chosen in DropDownList in the controller method. Thank you for any advice.
If you need it to bind to group_id then use that as the name:
#Html.DropDownList("group_id", ...)
Or, even better, use the strongly-typed helper:
#Html.DropDownListFor(m => m.group_id, ...)
Assuming you have a form field in your form with the name group_id like this and you want to set the selected value from your dropdown to that field for some reason,
#Html.HiddenFor(s=>s.group_id)
<div class="form-group">
#Html.DropDownList("groups",new SelectList(string.Empty, "Value", "Text"), "Choose...")
</div>
You can listen to the change event of the dropdown and get the selected option value and set to the group_id
$(function(){
$("#groups").change(function(e){
var v=$(this).val();
$("#group_id").val(v);
});
});
I am not sure why you are loading the dropdown content via javascript, but there are other better ways to render a dropdown and pass the selected value back to your controller as explained in this post.
Add a SelectedGroup property to your view model
public class CreateSomethingViewModel
{
public int SelectedGroup {set;get;}
public List<SelectListItem> Groups {set;get;}
}
and in your GET action, If you want to load the Groups, you can do it
public ActionResult Create()
{
var vm = new CreateSomethingViewModel();
//Hard coded for demo. You may replace with your db entries (see below)
vm.Groups = new List<SelectListItem> {
new SelectListItem { Value="1","Chase bank" },
new SelectListItem { Value="2","PNCbank" },
new SelectListItem { Value="3","BOA" }
};
return View(vm);
}
And in your view
#model CreateSomethingViewModel
#using(Html.BeginForm())
{
#Html.DropDownListFor(s=>s.SelectedGroup,Model.Groups)
<input type="submi" />
}
With this you do not need to use any js code ( Even if you load the dropdown content via javascript), when user changes the dropdown option value, It will be set as the value of the SelectedGroup property.
[HttpPost]
public ActionResult Create(CreateSomethingViewModel model)
{
// check model.SelectedGroup
// to do : Save and return/redirect
}
Related
I have a hard coded select list, pulling Value and Text from the db.
I have a specific item I want to set as the "default", so I order the list to specifically put it first in line ("Wip"). However, when the list is rendered in HTML, the order of the list is correct, but the selected value is the item with the smallest value, even though it is at the bottom of the list due to ordering descending.
Model:
public IEnumerable<SelectListItem> BinOptionsList { get; set; }
Data Access:
public IEnumerable<SelectListItem> PopulateBinList()
{
using (var db = new InventoryContext())
{
var data = db.StorageBin.OrderByDescending(s => s.BinCode == "Wip").ThenBy(s => s.BinCode).Select(s => new SelectListItem()
{
Text = s.BinCode,
Value = s.BinId.ToString()
}).ToList();
return data;
}
}
Controller:
model.BinOptionsList = dal.PopulateBinList()
View:
#Html.DropDownListFor(model => model.BinId, Model.BinOptionsList, new { #class = "form-control" })
The list renders in the View with "Wip" as the first selection, but the rendered "selected=selected" option is the item with id=0.
I know I can set the 'Selected' value in the Data Access method, but then I cant use this in an edit form that would already have a selected value.
Update - Rendered HTML:
<select class="form-control" data-val="true" data-val-number="The field Bin Code must be a number." data-val-required="The Bin Code field is required." id="BinId" name="BinId">
<option value="582">WIP</option>
<option value="595">0888</option>
<option selected="selected" value="0">0919</option>
<option value="1">1</option>
<option value="2">1A1</option>
<option value="3">1A10</option>
<option value="4">1A11</option>
</select>
I'm pretty sure BindId is equal to 0. If BindId is a simple Integer then it will always be equal to 0 by default. You'll need to set it to 582 yourself or set it as Integer? which would set the default as null.
So you may not prefer this answer but let me outline one quick thing. Your select list should not be of your model. The value selected from your select this should be part of your model. You are putting too much overhead into your model and it is having in impact on your view. Refactor it. Put your select list in your ViewBag for you to use in your view, stop passing it back and forth. This will keep your model compact and allow you to set your options properly.
Here is a simple example.
What would be your Data Access (just stubbing it out for example sake and yes setting it to static for example simplicity):
public static IEnumerable<SelectListItem> PopulateBinList()
{
return new List<SelectListItem>{ new SelectListItem {
Text = "WIP", Value = "582"
}, new SelectListItem {
Text = "0888", Value = "595"
} , new SelectListItem {
Text = "0", Value = "0919"
}, new SelectListItem {
Text = "1", Value = "1"
}};
}
Then your model (just adding the one property for example)
public class BinModel
{
public string BinId { get; set; }
}
In your controller
public ActionResult Index()
{
//load up your select list into the view bag
ViewBag.BinOptions = ViewHelper.PopulateBinList();
//preset the value of your desired object
var bm = new BinModel { BinId = "582" };
return View(bm);
}
The in your view you are going to bind to model property but use your temp list defined in the view bag to fill the options. Presetting your model's property will auto select which value is defaulted in the select list:
#Html.DropDownListFor(x => x.BinId, (IEnumerable<SelectListItem>)ViewBag.BinOptions, null, new { #class ="form-control" })
Please let me know if this does not make sense or needs to be expanded on.
I have an html dropdownlistfor which is being populated from my database, this I was able to do successfully but the issue I am having now is including an additional option not available in the database as an option that can also be selected.it is actually a list of items but I want a give an option ALL which when selected means the user is selecting all the items displayed in the database, my major issue is how to include the ALL option. I have searched and read similar questions but they are not what am trying to achieve. thanks for your help. here is my code
in my controller I have this:
var load = from bh in db.IV_001_ITEM
select bh;
ViewBag.selection = new SelectList(load.ToList(), "item_code", "item_name", glay.vwstring2);
in my view I have this:
<div class="col-sm-2">
#Html.DropDownListFor(m => m.vwstring2, ViewBag.selection as SelectList, "Select", new { #class = "form-control", required = "required", id = "selectc" } )
</div>
You can use the Add method to explicitly add an extra option (SelectListItem)
List<SelectListItem> optionList = db.IV_001_ITEM
.Select(x=>new SelectListItem { Value=x.item.code,
Text=x.itemName}).ToList();
// Now add the item you want
optionList.Add(new SelectListItem { Value="Foo",Text="Bar"});
//use this now
ViewBag.Items = optionList;
// You can set the selected item on your view model property
myViewModelObject.vwstring2 = glay.vwstring2; //For the selected item
return View(myViewModelObject);
In your view,
#Html.DropDownListFor(m => m.vwstring2, ViewBag.Items as List<SelectListItem>,
"Select", new { #class = "form-control"})
I have a dropdown I want to add to my _Layout.cshtml page in MVC 5. This is returned from Reference data in my Database - it is for CarTypes. There are 4 different types of car model that can be selected - Saloon, 4X4, Estate and Hatchback.
I created a CarTypesViewModel as below:
public IEnumerable<SelectListItem> CarTypesList { get; set; }
public string SelectedCarType { get; set; }
I then have a view :
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
//Just a html div here perhaps?
#Html.DropDownListFor(model => model.SelectedCarType, Model.CarTypesList)
}
Within the layout i have the following:
<li id="selectedcar">#Html.Action("Index", "CarTypes")</li>
This then goes to this action in my CarTypes controller:
var model = new CarTypesViewModel
{
CarTypesList= products.Select(p => new SelectListItem
{
Value = p.Id.ToString(CultureInfo.InvariantCulture),
Text = p.Name
})
};
return View(model);
This is returning the data to the Dropdown list. However what I really want is for a Value to appear like Please Select Your Car Type as the first item in the list - what is the best way to achieve that as I dont want to store that as a value in my database?
#Html.DropDownListFor(model => model.SelectedCarType,
new SelectList(Model.CarTypesList, "Value", "Text"),
"--- Please Select Your Car Type ---",
new { #class = "form-control" }
)
Pass in the optionLabel argument to DropDownListFor.
See: http://msdn.microsoft.com/en-us/library/ee703561(v=vs.118).aspx
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
//Just a html div here perhaps?
#Html.DropDownListFor(model => model.SelectedCarType, Model.CarTypesList, "Please Select Your Car Type")
}
This should do it.. (Adding your custom text as 3th element.)
I have created a DropDownList which is initialized from code behind like that :
Code Behind :
List<SelectListItem> ddlIsActivated = new List<SelectListItem>
{
new SelectListItem
{
Text = "Activated",
Value = "0"
},
new SelectListItem
{
Text = "Not activated",
Value = "1"
}
};
ViewBag.ddlIsActivated = ddlIsActivated;
View :
<div class="row">
<div class="form-group col-xs-3">
#Html.DropDownList("IsActivated", ViewBag.ddlIsActivated as List<SelectListItem>, "Default")
</div>
</div>
When I click directly on the search button after the load, the DropDownList has "Default" as the first item and my URL looks like that :
http://localhost:51817/Log?SearchString=&IsActivated=
Is it possible to specify that all parameters with an empty value might not be passed on the URL ?
In case of the DropDownList, is it possible to avoid the param "IsActivated" when the "Default" is Selected ?
Sure one way is when the submit button is clicked or activated, you set the fields that are the default value to disabled. then they don't go in the post.
Example of using jQuery onsubmit:
How to use jQuery to onsubmit and check if the value is 2 - 5 characters?
You can try having a separate viewmodel, with properties for the list of options and the selected option. In the GET request action method, you can populate this list and render the view, and in the POST action method, you can exclude this property during model binding, so that only the selected item property will get bound. Thus, you don't need ViewBag or routeValues or querystring parameters, and your URL will always look clean.
EDIT:
This is how you might do it.
public class ViewModel
{
public int SelectedId { get; set; }
public Dictionary<int,string> OptionList { get; set; }
}
And then in your view,
#Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.OptionList, "Key", "Value"), null, null)
In your GET action method,
Dictionary<int,string> OptionList = GetOptionList(); // Populate from DB
return View(new ViewModel { OptionList = OptionList });
Also, remember to [Bind(Exclude="OptionList")] in your POST action method.
I have an MVC3 application with Razor and I created a View that inside renders a Partial View. This is how the main View looks like:
#{Html.RenderPartial("_SearchFilters", Model.SearchFilters);}
#* Other HTML elements *#
Inside the _SearchFilters Partial View I have the following DropDownLists inside a Form element:
Choose Year
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text"), DateTime.Now.Year)
Choose Month
#Html.DropDownListFor(m => m.Month, new SelectList(Model.MonthsList, "Value", "Text"), Model.Month.ToString(), new { #disabled = "disabled" })
<input type="submit" value="Display" />
I would like that upon Submit the two DropDownLists keep their status, namely the value selected by the user, when the View is reloaded with the filtered data.
Is there any way to do it without using AJAX?
UPDATE
The ViewModel is as follows:
public class TableSearchFiltersViewModel
{
public bool YTM { get; set; }
public int? Month { get; set; }
public int? Year { get; set; }
public IEnumerable<SelectListItem> YearsList
{
get
{
return Enumerable.Range(2011, (DateTime.Now.Year - 2011 + 4)).Select(m => new SelectListItem
{
Value = m.ToString(),
Text = m.ToString(),
}).OrderBy(m => m.Value);
}
}
public IEnumerable<SelectListItem> MonthsList
{
get
{
return Enumerable.Empty<SelectListItem>();
}
}
}
Thanks
Francesco
When you submit the form to the corresponding controller action, this action should take as input parameter some view model. This view model's properties will be bound from the input fields contained in the form including the selected value of the two dropdowns. Then the controller action could return the same view which will preserve the selected values of the dropdown boxes.
I would recommend you to use Editor Templates though instead of rendering partials as this will ensure proper naming of the dropdowns and eventually preserve selected values:
#Html.EditorFor(x => x.SearchFilters)
I don't have IDE at this time so couldn't test but this might work:
Choose Month
EDIT:
#Html.DropDownListFor(m => m.Month,
Model.MonthsList.Select(
t => new SelectListItem {
Text = t.Name,
Value = t.Value,
Selected = t.Value == Model.Month,
},
Model.Month.ToString(), new { #disabled = "disabled" })
Without ajax not, or you will have to repost the whole form. MVC is a web framework which is not dynamic like a winforms application. You will have to post the changes to your controller and reload the page with the necessary changes, or use ajax to reload these changes.
You could provide the default values for Year and Month properties (to be selected at the first request) and bind those instead of the hardcoded startup values you provided.
So instead of:
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text"), DateTime.Now.Year)
Which btw seems erroneous, as selected value (which I suppose DateTime.Now.Year is in your example) should be provided as SelectList's constructor (instead of DropDownListFor method's) argument. DropDownListFor method doesn't have a 'selected value' argument.
You could write:
#Html.DropDownListFor(m => m.Year, new SelectList(Model.YearsList, "Value", "Text", Model.Year))
and analogously in the second dropdown.
This will make dropdowns keeps the selected values when rendered using the posted model (as Model.Year and Model.Month would hold those). So you should make sure those values won't get overwritten with default ones after subsequent submits.