In my ViewBag there is object that contains Id,First name and Last name. I want to display DropDownList that has Id as value and "First name"+" "+"Last Name" as text.
#Html.DropDownListFor(model => model.Id, new SelectList(ViewBag.person, "Id","Last Name"), new { #class = "form-control" })
This is the line of code that I use currently, how can I modify it to display the right info?
You have to modify your controller and model to send the concatenated text to the View, or create a new SelectList in the View itself that concatenates the values before passing it to the DropdownListFor.
What you are trying to achieve would be possible if SelectList had an overload with a callback for formatting, but this isn't possible.
Related
I have the following declaration in Razor:
#Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>, ViewBag.CurrentUserRole as string, new { #class = "form-control" }), and it results in a drop-down that looks as follows on page load:
And when I click on the dropdown arrow, I see:
So basically, the User Role is duplicated. How can I change this so that instead of making a new duplicate element, it defaults to the element it is supposed to be? Basically, since ViewBag.RolesEdit is a list, and ViewBag.CurrentUserRole is guaranteed to have an element that is equal to exactly one item in the afformentioned list, how can I loop through the list to compare each other and set the default?
Thank You.
When using Html.DropDownList helper method, To set one option to be pre selected, you just need to set the value of that option to the the ViewBag dictionary with the same key used to generate the SELECT element.
#Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>)
Assuming your action method is setting ViewBag.SelectedRole to the value of the option you want to select.
ViewBag.RolesEdit= new List<SelectListItem>{
new SelectListItem { Value="Administrator", Text="Administrator"},
new SelectListItem { Value="Employees", Text="Employees"},
new SelectListItem { Value="RegularUser", Text="Regular User"},
}
ViewBag.SelectedRole ="RegularUser";
return View();
If you prefer to use Html.DropDownListFor helper method with a strongly typed view and view model, you can follow this post
What is the best ways to bind #Html.DropDownListFor in ASP.NET MVC5?
Im kinda stuck, I have a drop down that I am trying to combine two fields from the same table into. Its kinda working, here is what I get:
The offending drop down list
As you can see, im pulling stuff I dont want into it, and im not pulling in my last name.
Here is my edit controller:
var DocList =
db.Doctors
.Select(s => new
{
Value = s.ID,
FirstN = s.FirstName,
SurN = s.Surname,
})
;
ViewBag.Doctor = new SelectList(DocList, "FirstN", "SurN", episode.Doctor.ID);
and here is my razor snippet:
#Html.DropDownList("docTest")
What do you guys think is going wrong here? Thanks in advance! :)
Looks like you may be needing to do something like this (it will give the dropdown the id of "docTest"):
#Html.DropDownList("docTest", (SelectList)ViewBag.DoctorOLD, "Place Holder Text", new { #class = "someClass" })
but you may need different functionality, I cannot tell from the amount of code supplied.You may also look into using #html.DropDownListFor if you need to bind the drop down value to a model property.
This SO post here does a great job of explaining html helper drop down list.
You are not binding the value to drop down list.Use below code to get the values
#Html.DropDownList("docTest",(IEnumerable<SelectListItem>)ViewBag.DoctorOLD)
Okay here is the solution im still pretty green at this so where I came unstuck was knowing the overloads. Let me try to explain (and correct me if im wrong)
Okay so we invoke our list. Now our first overload is the ieneumerable, this gets our bunch of stuff we want in our list. Next we want our value field, which is the column in your table that other tables use to link to it, in most cases its the ID column.
Next is the string. In my case its "FullName" and is basically made up of the FirstName and Surname from within my Doctors table.
Anyway if your dyslexic like me just look at the code below and pick it apart :)
The Controller:
ViewData["docFullDetails"] =
new SelectList((from s in db.Doctors
select new
{
FullName = (s.FirstName + s.Surname),
ID = s.ID
}),
"ID",
"FullName");
The View:
<div class="form-control">
#Html.DropDownList("docFullDetails")
#Html.ValidationMessageFor(model => model.Doctor)
</div>
In your controller you should populate your dropdown list like
ViewBag.Doctors = new SelectList(db.Doctors.Select(d => new { d.Id, FullName = d.FirstName + " " + d.LastName }),
"Id", "FullName");
And then in view create dropdown with razor
#Html.DropDownList("DoctorId", ViewBag.Doctors as SelectList, "Select doctor...", new { #class = "form-control" })
Your model for form that you are creating probably should have DoctorId property which you are binding from dropdown
#Html.DropDownListFor(m => m.DoctorId, ViewBag.Doctors as SelectList, "Select doctor...", new { #class = "form-control" })
I got a ViewModel graph with some sub-objects.
This code:
#Html.DropDownListFor(model => model.JobTypeParams.ContactCatalogId, new SelectList(paramz.ContactCatalogues, "Id", "Description"), new { #class = "select2 input-default " })
Generates a Request.Form key/value item with the key of: JobTypeParams.ContactCatalogId.
That's great because that means the MVC Model Binder can correctly map the key/value item to the corresponding field in the view model.
However! This code (using casts)
#Html.DropDownListFor(model => ((AdSyncJobSpecificParameters)model.JobTypeParams).ContactCatalogId, new SelectList(paramz.ContactCatalogues, "Id", "Description"), new { #class = "select2 input-default " })
Generates a Request.Form key/value item with key ContactCatalogId. It loses the JobTypeParams prefix somewhere.
This leads to the modelbinder being unable to bind correct key to correct viewmodel field, and hence the problem.
I do not want to hard-code the ID because of many reasons. So how do you get the HTML Helper to correctly generate they name of the Name/Id attribute ?
It doesn't get them wrong, it's not supposed to do that. You have an incorrect expectation of how lambda's work. You are effectively replacing the old expression, model.JobTypeParams with a single expression of type AdSyncJobSpecificParameters.
What you should be doing is using an editor template.
#Html.EditorFor(model => model.JobTypeParams)
Then, create a AdSyncJobSpecificParameters.cshtml in your EditorTemplates folder and do this:
#model AdSyncJobSpecificParameters
#Html.DropDownListFor(model => model.ContactCatalogId,
new SelectList(paramz.ContactCatalogues, "Id", "Description"),
new { #class = "select2 input-default " })
You'll need to figure out a solution for the SelectList, since it doesn't seem to be part of your model. Maybe as a ViewBag item.
You can also create one for your superclass as well in YourSuperclass.cshtml
#model YourSuperclass
// etc...
I am using MVC4, just wondering, is it possible to update the name attribute of a html helper. I am updating this as the action method is expecting a particular name. I know I can just write raw html, but just want to know if there is an overide in the html helper
I tried this
#Html.TextAreaFor(m => m.noteDetail.NotesDetails, new { #class = "k-textbox", #cols = 100, #rows = 5, id="NotesDetails", name= "NotesDetails" })
but when I look at the generated html
<textarea class="k-textbox" cols="100" data-val="true" data-val-required="The details are required" id="NotesDetails" name="noteDetail.NotesDetails" rows="5"></textarea>
Thanks
You just need a # symbol in front of your name property.
One technique I've found when a submodel is the model that your POST action accepts is to put the HTML that renders the submodel in a partial view that's included in the main view. Have this partial by strongly typed by the submodel and pass the value of the submodel into it. This way, the prefixes won't be generated on the submodel.
#Html.Partial("_NoteDetails", Model.noteDetail)
Then in _NoteDetails.cshtml
#model NoteDetail
#Html.TextAreaFor(m => m.NoteDetails,
new { #class = "k-textbox", cols = 100, rows = 5 });
Hi I think as you pass a viewModel as it contains maybe 2 models that is why you have this name. It does like this for the Binder to construct objects from your Post or Get.
If you change the name then you will maybe perform some custom codes for your binder if you want to pass it again to the controller.
I am trying to populate a drop down list of items. I am using MVC4 with the twitter bootstrap styling, on visual studio 2012.
The code that I have for the controller is:
String[] genders = { "Male","Female","Other"};
ViewBag.genders = new SelectList(genders);
And in my view is:
#Html.DropDownListFor("genders", "Select a gender", new { #class = "form-control" })
However, I get an error:
'The type arguments for method
'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
System.Linq.Expressions.Expression>,
System.Collections.Generic.IEnumerable,
object)' cannot be inferred from the usage. Try specifying the type
arguments explicitly.'
I have tried various other forms of the statement. But basically I would like to keep the controller as is and edit the statements in the view. But I am open to anything which people are willing to suggest that will help me solve this issue.
Thanks in advance
Try this:
#Html.DropDownListFor(m=>m.SelectedGender, (SelectList)ViewBag.genders, "Select gender", new { #class = "form-control" })
m=>m.SelectedGender, is where you bind the value to something in your view's model (or if you have no model, you should use #Html.DropDownList supplying a string instead).
#Html.DropDownListFor expect a lamda expression, not a string as it first parameter.
Now... to use a DropDownListFor... you need a Model in your view. That model should have a Property where you will store the selected value when you post the form where the DDL is in.
#Html.DropDownListFor(m=>m.Gender, (SelectList)ViewBag.genders, "Select gender", new { #class = "form-control" })
Now, if you don't have a model in your view... you should use #Html.DropDownList()
In this case, you can just enter a name as a first parameter.
#Html.DropDownList("SelectedGender", (SelectList)ViewBag.genders, "Select gender", new { #class = "form-control" })