Help with asp.net mvc select dropdown - asp.net-mvc

I have a marital status field in my users table that its just varchar
yet I only want to give the users four options (married, single, widowed and divorced) and i want to have the correct one selected when Im editing the form.. is it possible? please help.

This should point you in the right direction:
<%= Html.DropDownList("listName", new string[] { "Married", "Single", "Widowed", "Divorced" }
.Select(m => new SelectListItem(){
Selected = model.MaritalStatus == m,
Text = m,
Value = m
})); %>
Assuming that your model has a 'MaritalStatus' field,
Selected = model.MaritalStatus == m
will select the status of your model by default.

This blog post should lead you in the right direction:
http://weblogs.asp.net/ashicmahtab/archive/2009/03/27/asp-net-mvc-html-dropdownlist-and-selected-value.aspx
you'd have to give us a little more information and maybe a code sample of what you have so far to get a more specific answer.

Related

How to display data in the dropdownlist for the Dev express mvc grid

I have a dev express grid with 3 columns in it and I want the 3rd column to be editable.
When a user clicks on edit then a drop down list should display for that row (only in the 3rd column), but each row should have a different drop down list as I want to pull data from different stored procedures based on the field name.
So, I am able to get a grid with 3 columns and first two columns are non-editable and also, I have a drop down for the 3rd column but I do not know how to display the data in the drop down for each row. That is where I am stuck.
This is what I have written so far :-
Partial View :-
settings.Columns.Add(col =>
{
col.FieldName = "DefaultValue";
col.Caption = "Rule Type Value";
col.Width = 300;
col.ColumnType = MVCxGridViewColumnType.DropDownEdit;
col.SetEditItemTemplateContent(column =>
{
Html.DevExpress().DropDownEdit(c =>
{
c.Name = "ddlName";
c.SetDropDownWindowTemplateContent("WHAT GOES HERE!?!?!");
}).Render();
});
});
It would be great if anybody can help me on that.
If I have not given adequate information to explain this question then please let me know.
For your dropdownedit you want to add items this way:
c.Properties.Items.Add("Item 1");
c.Properties.Items.Add("Item 2");

Drop down list with already defined Values MVC2

I am trying to create a pre-defined drop down list for C# ASP.NET MVC2. I am way confused on how to get this done... Boy did we have it easy in vanilla asp.net...
But, let say I wanted the drop down list to have simple text like ... BMW, Audi, Mercedes, and values such as 1, 2, 3 or even "good", "better", "Best"... How would I create the Drop down list in the controller and how would I get it to the View?
What I have right now is
List<SelectListItem> MRNList = new List<SelectListItem>
{
new SelectListItem { Text = "BMW", Value = "good", Selected = false},
new SelectListItem { Text = "Audi", Value = "better"},
new SelectListItem { Text = "Mercedes", Value = "Best"},
};
ViewData["MRNDROPDOWNLIST"] = MRNList.AsEnumerable();.
In my view I have...
<%:Html.DropDownListfor("MRN", ViewData["MRNDROPDOWNLIST"]) %>
What am I missing here? I am getting a compile time error from Visual Studio telling me that I can't do that? But the Parameter for DropDownList definitely says that you can use An IEnumerable list to fill that param? I know I am missing something obvious here... Not sure what it is just yet... I will keep looking, but if any of you have any clues I would definitely appreciate it.
Derek
ViewData["MRNDROPDOWNLIST"] is of type object and you will need to cast that to the correct type for the error to go away, which in this case would be to List<SelectListItem>:
<%:Html.DropDownListfor("MRN", (List<SelectListItem>)ViewData["MRNDROPDOWNLIST"])%>

DropDownListFor Not Displaying/Persisting Null for First Choice in List

I have an MVC app via SharpArch. In the view I have:
Html.DropDownListFor(x => x.Location,
new SelectList(Model.PossibleLocations, "Id", "Address"),
"-- No Location --")
I have 2 issues.
The Dropdown is not getting updated when the view gets bound to the model.
A selection gets persisted correctly except when I try the top "no location".
I was able to take care of the first point by changing x.Location to x.Location.Id but then I had other issues.
I can find plenty of examples for DropDownList, but none in which saving a null is shown.
Any help is appreciated.
Thanks
UPDATE:
I just upgraded Resharper (a minor update) and am getting prompted to fill it DropDownListFor. Why would that make a difference? It was working enough to bind and now it doesn't work at all.
You could always insert the "empty" SelectListItem into your PossibleLocations collection before passing to the View and check for that "empty" value (0 for instance) when the form is posted
model.PossibleLocations.Insert(0,
new SelectListItem() { Text = "-- No Location --", Value = "0" };
Try "flattening" your model class so that LocationId is the actual value you're binding to (i.e. add a "LocationId" property to your model, and create a DropDownList for x => x.LocationId).

Getting all selected checkboxes from a FormCollection

I have a form which contains a whole bunch of checkboxes and some other types of control too. I need to retrieve the names of each selected checkbox.
What is the best way to do this? Can I do it with a linq query maybe?
So in pseudocode, I'm looking to do something like this:
var names = formCollection
.Where(c => c is Checkbox && c.Checked)
.Select(c => c.Name);
Update It seems the way MVC submits checkboxes is different from how a normal form would behave, as an hidden field is also rendered. I found the details here: How to handle checkboxes in ASP.NET MVC forms?
Anywho, I've got it working with the help of that thread and the answer from BuildStarted below. The following code did the trick.
var additionalItems = form.AllKeys
.Where(k => form[k].Contains("true") && k.StartsWith("addItem"))
.Select(k => k.Substring(7));
Unfortunately that type of information isn't available in the collection. However if you prepend all your checkboxes with something like <input type='checkbox' name='checkbox_somevalue' /> then you can run a query like
var names = formCollection.AllKeys.Where(c => c.StartsWith("checkbox"));
Since only the checked values will be posted back you don't need to validate that they're checked.
Here's one that grabs only checked values
var names = formCollection.AllKeys.Where(c => c.StartsWith("test") &&
formCollection.GetValue(c) != null &&
formCollection.GetValue(c).AttemptedValue == "1");
This is one of the old questions not active for years but I stumbled on it. My problem was that I have an array of check boxes - let's say the name is 'IsValid' and wanted to get the status of each of the check boxes (my project was in MVC 5). On form submit i did the loop of form collection and got the values as...
if (key.Contains("IsValid"))
sV = (string[])collection.GetValue(key.ToString()).RawValue;
Since on form post the hidden field value was also posted with the checked check boxes; the array contained one additional value of 'false' for ONLY checked check box. To get rid of those i used following function; I hope that it helps somebody and if my approach is wrong then a better solution would be helpful to me as well!
sV = FixCheckBoxValue(sV);
private string[] FixCheckBoxValue(string[] sV)
{
var iArrayList = new List<string>(sV);
for (int i = 0; i < iArrayList.Count; i++)
{
if (iArrayList[i].ToString() == "true")
{
iArrayList.RemoveAt(i + 1);
}
}
return iArrayList.ToArray();
}
Answering the post about the array of checkboxes, you could initially filter out the checkboxes by name.
var keys = formCollection.AllKeys.Where(x => x.StartsWith("IsValid");
Then you could just loop through them as a collection.

HTML.DropDownList does not respect pre-selected value

I want to use Html.DropDownList(string name, IEnumerable SelectList, Object htmlAttributes) to render a select list with a preselected value for me.
My select list is in the model object of my view, so I have been writting the following code:
<%= Html.DropDownList("aName", mySelectList, new { }) %>
Which will render the select list without the pre-selected value.
A workaround I have found is passing the SelectList as ViewData and doing the following:
In the controller:
ViewData["TimeZones"] = mySelectList;
In the view:
<%= Html.DropDownList("TimeZones", null, new { }) %>
This way the select list will be rendered with the preselected value, however, I don't want to be forced to pass my select list as view data. What am I doing wrong? Thank you in advance for your help.
You can simply do this (it works):
<%: Html.DropDownList("DropdownName", new SelectList(ListItems, "Value", "Text", selectedItem), htmlAttributes)%>
Let me know in case this does not work for you.
Autobinding the selected item
The other approach is to automatically bind the selected item, and passing the list of items as parameter to the DropDownList helper method.
In the controller you do exactly the same thing as before, just don’t set to true the Selected property of any item. Then you also have to put into the view model the value of the item you want to select.
var model = new IndexViewModel()
{
ListItems = items,
SelectedItem = 2
};
And finally in the view, you use the overload which accepts also the selectList parameter:
<%= Html.DropDownList("SelectedItem", Model.ListItems) %>
The only difference in the HTML rendered is that, with first approach, the name of the HTML select element is ListItems, with the second it is SelectedItem.
These approaches are fine if you are creating your own list, but they are not the optimal solution if you are receiving the list of options for an external method, for example from a DB repository.
Take a look at this link
I know this is an old post, but I ran into a similar issue in MVC5. The solution is simple, but I struggled with it for a while, so I thought I'd share.
VS auto-generates DropDownLists with this in the view:
#Html.DropDownList("EpisodeTypeId", null, htmlAttributes: new { #class = "form-control" })
In the controller, VS auto-generates the ViewBag code differently for a Create vs. and Edit.
Here's the code from a create:
ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name");
And from an edit:
ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name", episode.EpisodeTypeId);
That fourth argument is important for Edits, as you might expect. If you leave it out, the database value for that record will not be pre-selected in the DropDown.
The VS auto-generated code will be correct, but if you're adding in fields manually later, this is easy to miss.

Resources