Add custom text to Dropdown list for MVC 5 - c#

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.)

Related

add extra option to an already populated dropdownlist in mvc

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"})

DropDownListFor How to set a default value from a database

So, I got a DropdownListfor that looks like that in my view:
#Html.DropDownListFor(m => m.ProductCategory, new SelectList(Model.ProductCategories.OrderBy(m => m.PCNumber), "", "Name"), "")
That works like it should. In my next view the user should be able to edit his order. So what I want to do is, if he opens the form all of his data from before should be displayed, for textboxes I got it work with the following code:
#Html.TextBoxFor(m => m.NameOfProduct, new { #Value = #Model.NameofProduct })
So now my problem is how can I do the same thing that I did with my textboxes (giving them default values from my model) for a DropDownListFor when the value is stored in my model(database)? It should like that if he selected Category 3 before and now wants to edit his order from before, the dropdownlist should show category 3 right away.
Thank you for any help!
Try this code may be it work in your situation.
#Html.DropDownListFor(m=> m.PCNumber, new SelectList(m.ProductCategories, "PCNumber", "ProductCategory"), "-- Select Category --", new { #class = "form-control" })
here you will get default edit order in your dropdown
[HttpGet]
public ActionResult EditOrder(int? id)
{
_obj_order_detail = db.order_detail.Find(id);
if (_obj_order_detail != null)
{
_obj_order_detail.ProductCategories = db.category_detail.ToList(); //get category List
return View(_obj_order_detail);
}
else
{
return view();
}
}
this will return view with order which you want to edit and ProductCategories and dropdown bu default contain ProductCategory which you want to edit

Getting the chosen item from DropDownList

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
}

How to save my dropdown list selected Item into my database?

I need to save a selected Item in my Database during User Registration. but it seems as if my selected Item is not recognised. here is the error that it's givin me
"There is no ViewData item of type 'IEnumerable' that
has the key 'Faculties"
Am still unskilled in MVC/C# Programming please help here is my code below; thanks in advance!
My DataModel
public string Faculty { get; set; }
My Controller
public ActionResult Register()
{
DataClasses1DataContext db = new DataClasses1DataContext();
ViewBag.Faculties = new SelectList(db.Faculties, "Id", "Name");
return View();
}
My View
<div class="form-group">
#Html.LabelFor(model => model.Faculty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Faculties","Select Faculty")
#Html.ValidationMessageFor(model => model.Faculty, "", new { #class = "text-danger" })
</div>
</div>
The way you are displaying items in the dropdown is not correct. You can use below code to display the items fetched from your db:
#Html.DropDownList("Faculties", ViewBag.Faculties as IEnumerable<SelectListItem>,
"Select Faculty");
Please note that your ViewBag.Faculties should be casted to Enumerable<SelectListItem>.
To get the selected value of dropdown in controller you can use below method:
var value = Request["Faculties"];
Once you got the value, you can save it in database.
Update:
A good approach will be to bind your View to a model which I think you have already done since I can see you are using model.Faculty. So the dropdown should look something like below in View:
#Html.DropDownList(model => model.Faculty,ViewBag.Faculties as IEnumerable<SelectListItem>,
"Select Faculty");
And your controller where data is posted should be something like below:
[HttpPost]
public ActionResult Register(YourModel model)
{
var selectedFaculty = model.Faculty; //Selected Value
//Save it in database
}
Try changing this line:
ViewBag.Faculties = new SelectList(db.Faculties, "Id", "Name");
to the following
ViewData["Faculties"] = new SelectList(db.Faculties, "Id", "Name");
ViewBag and ViewData are two separate constructs, and cannot be used interchangeably.
It's just the names of your property and your ViewBag are different. change your ViewBag name to match the property name.
ViewBag.Faculty = new SelectList(db.Faculties, "Id", "Name");
Your HTML would be:
#Html.DropDownList("Faculty ","Select Faculty")
Alternatively and (preferably) use a model binding instead of ViewBag
Model
public string Faculty { get; set; }
public IList<SelectListItem> Faculties {get;set;}
Controller
Model.Faculties = new SelectList(db.Faculties, "Id", "Name");
return View(Model);
HTML (View)
#Html.DropDownListFor(m => m.Faculty , Model.Faculties )

Reloading an ASP.NET MVC3 Partial View without using AJAX

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.

Categories