Handling onchange event in HTML.DropDownList Razor MVC - asp.net-mvc

I'm handling an onchange event with a selected value by simple HTML like this:
<select onchange="location = this.value;">
<option value="/product/categoryByPage?PageSize=15" selected="selected">15</option>
<option value="/product/categoryByPage?PageSize=30" selected="selected">30</option>
<option value="/product/categoryByPage?PageSize=50" selected="selected">50</option>
</select>
Doing it like this:
List<SelectListItem> items = new List<SelectListItem>();
string[] itemArray = {"15","30","50"};
for (int i = 0; i < itemArray.Count(); i++)
{
items.Add(new SelectListItem
{
Text = itemArray[i],
Value = "/product/categoryByPage?pageSize=" + itemArray[i]
});
}
ViewBag.CategoryID = items;
#Html.DropDownList("CategoryID")
How can I handle onchange with #Html.DropDownList()

Description
You can use another overload of the DropDownList method. Pick the one you need and pass in
a object with your html attributes.
Sample
#Html.DropDownList("CategoryID", null, new { #onchange="location = this.value;" })
More Information
MSDN - SelectExtensions.DropDownList Method

The way of dknaack does not work for me, I found this solution as well:
#Html.DropDownList("Chapters", ViewBag.Chapters as SelectList,
"Select chapter", new { #onchange = "location = this.value;" })
where
#Html.DropDownList(controlName, ViewBag.property + cast, "Default value", #onchange event)
In the controller you can add:
DbModel db = new DbModel(); //entity model of Entity Framework
ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

Related

selecting an option in html.dropdown helper method using boolean result

I am working on an asp.net application. I have a viewbag with a boolean result (true or false) and I need to select one option from a razore view using this viewbag. I have done it like this.
Controller:
ViewBag.AMZ = result.shipment.ShipAMZ ;
View:
#{
var IsAmzSelected = (bool)ViewBag.AMZ;
}
<select id="amz" name="amz" class="form-input">
#if (IsAmzSelected == true)
{
<option value='1' selected>AMZ</option>
<option value='0'>BBW</option>
}
else
{
<option value='1'>AMZ</option>
<option value='0' selected>BBW</option>
}
</select>
I tried using Html dropdownlist helper method but it didn't work.
in controller i did it like this:
ViewBag.AMZ = new SelectList(new List<SelectListItem>() { new SelectListItem() { Text = "AMZ", Value = "1" }, new SelectListItem() { Text = "BBW", Value = "0",Selected=true } }, "Value", "Text" , result.shipment.amz);
and then bound it to htmldropdown to this viewbag but it didn't work
Can you please suggest how to do it using html.dropdown?

Razor #Html.DropDownList() do not take the selected value from List<SelectListItem> selected value

In my controller a have this:
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = row["ProgramName"].ToString().Trim(),
Value = row["Id"].ToString().Trim(),
Selected = row["selected"].ToBoolean()
});
but when I send the object to the razor view I get it like this
#Html.DropDownList("ListaProgramas", (IEnumerable<SelectListItem>)ViewData["ListaProgramas"], new {#class = "form-control pull-left", #id = "ListaProgramas", #style = "color:black; width:100%;" })
That look like this:
but Razor not set selected value. What i would do for resolve this issue ?
The HTML is this
<select class="form-control pull-left" id="ListaProgramas" name="ListaProgramas" style="color:black; width:100%;">
<option selected="selected" value="1">VIADR</option>
<option value="2">TweakedBPclient</option>
</select>
But in my controller I selected a different one
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = row["ProgramName"].ToString().Trim(),
Value = row["Id"].ToString().Trim(),
Selected = valor
});
I want HTML Razor view take as selected the element that I selected in the controller code.
When crafting your SelectList, use this form instead:
new SelectList(ViewData["ListaProgramas"], "Value" , "Text", itemToSelect);
Where itemToSelect is the appropriate row["Id"] - since you don't have a model in play, you can pass this value in via the ViewData, as well. That being said, I also advise using strongly-typed views and helpers and simply setting the value in the model that is passed to the view, thereby cutting out the need to specify the itemToSelect parameter altogether.

ASP.NET MVC (razor) Listbox multiselect values to string

I have two multi-select list boxes; one with months and one with years such as the following:
#Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeMonths, Model.TimeframeMonths)
#Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeYears, Model.TimeframeYears)
I'm saving the both values to the database as a comma separated list (string/nvarchar). The values are being like this: Months: 1,3,7; Years: 2002,2005
For some reason when I pull the values back out to the form, the months are pre-selecting in the listbox fine, but the years are not.
Any ideas?
EDIT - Additional code samples:
Controller - Manage
public ActionResult Manage(Guid id)
{
var list = _listService.GetList(id);
var model = LoadModelFromObject(list);
model.TimeframeMonths = GenerateMonthDropdown();
model.TimeframeYears = GenerateYearDropdown(model.IncludeGuestsArrivedInTimeframeYears.Split(','));
model.DaysOfWeek = GenerateDaysOfWeekDropdown();
return View(model);
}
Controller - 'Helper'
private IList<SelectListItem> GenerateYearDropdown(string[] selected)
{
var list = new List<SelectListItem>();
var startYear = DateTime.Now.Year - 10;
for (int idx = startYear; idx < startYear + 11; idx++)
{
list.Add(new SelectListItem
{
Value = idx.ToString(),
Text = idx.ToString(),
Selected = selected != null && selected.Contains(idx.ToString())
});
}
return list;
}
View
#Html.CheckBoxFor(m => m.IncludeGuestsArrivedInTimeframe)
#Html.LabelFor(m => m.IncludeGuestsArrivedInTimeframe)
#Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeMonths, Model.TimeframeMonths)
#*#Html.ListBoxFor(m => m.IncludeGuestsArrivedInTimeframeYears, Model.TimeframeYears)*#
#Html.ListBox("IncludeGuestsArrivedInTimeframeYears", Model.TimeframeYears)
You need to set Selected property of SelectItemList class to true for the options which you want to be pre-selected.
Example:
#{
var foo = new List<SelectListItem> {
new SelectListItem { Text = "Foo 1", Value = "1", Selected = true },
new SelectListItem { Text = "Foo 2", Value = "2" },
new SelectListItem { Text = "Foo 3", Value = "3", Selected = true }
};
}
#Html.ListBox("foo", foo)
In this case, Foo 1 and Foo 3 should appear as pre-selected. The above code generates the below html markup:
<select id="foo" multiple="multiple" name="foo">
<option selected="selected" value="1">Foo 1</option>
<option value="2">Foo 2</option>
<option selected="selected" value="3">Foo 3</option>
</select>
Edit:
First of all, replace this code:
list.Add(new SelectListItem {
Value = idx.ToString(),
Text = idx.ToString(),
Selected = selected != null && selected.Contains(idx.ToString())
});
with this code:
list.Add(new SelectListItem {
Value = idx.ToString(),
Text = idx.ToString(),
Selected = true
});
Then run the app. If all the options are pre-selected, then I bet that this selected != null && selected.Contains(idx.ToString()) does not satisfy the condition.
Another way of doing it
#Html.ListBox("categoryId", new MultiSelectList(ViewData["categories"] as System.Collections.IEnumerable, "Id", "CategoryName", Model.tIdx_ProductCategories.Select(x => x.CategoryId).AsEnumerable()))
Explanation:
categoryId - would be name of control, when rendered as html
ViewData["categories"] - is list of categories with Id and CategoryName properties
Model.tIdx_ProductCategories carries the list of category ids to be selected in list box.
As it seems (e.g. here Preselect Items in Multiselect-Listbox (MVC3 Razor)) the Razor engine happily ignores the Selected property and compares the list from the model and the supplied option list by calling ToString() on the objects from the model and using string comparison to select.
What I cannot explain to myself is why this behavior is used with Html.ListBox(), which does not use any model and expects a collection of SelectListItem.
Think it's a bug, but it does not seem to have been addressed recently.

Can I change the html name generated by Html.DropDownListFor?

IDI am using the following code to create a drop down list:
#for (var index = 0; index < Model.AdminSummaries.Count(); index++)
{
<div class="rep_tr0">
<div class="rep_td0">
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status, AdminStatusReference.GetAdminStatusOptions())
</div>
The code creates the following:
<select id="AdminSummaries_2__Status" name="AdminSummaries[2].Status">
<option value="1">Released</option>
<option value="2">Review</option>
<option value="3">New</option>
</select>
<select id="AdminSummaries_3__Status" name="AdminSummaries[3].Status">
<option value="1">Released</option>
<option value="2">Review</option>
<option value="3">New</option>
</select>
Is there any way that I could change it so that it creates a ID of "Status_2", "Status_3" etc.
As #Anar said in the comments;
Actually, you can change the name attribute the same way as id, but instead of "name", use "Name". Surprisingly it works.
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status,
AdminStatusReference.GetAdminStatusOptions(),
new { id = string.Format("Status_{0}",index ), Name = "GiveName" });
Sometimes the HTML helpers don't HELP. DropDownListFor coding can get complicated real fast and in the end it's just rendering HTML so sometimes it's better to go old school
<select name="myname" class="dropdownlist" id="myid">
#foreach (SelectListItem item in Model.SomeSelectList) {
if (item.Value == Model.theValue) {
<option value="#(item.Value)" selected="selected">#item.Text</option>
} else {
<option value="#(item.Value)">#item.Text</option>
}
}
</select>
For those wondering why this doesn't work, the whole thing is case sensitive and need an # in front of it...
so, this works:
new { #id = "myID", #Name = "myName", #Value = "myValue", #class = "form-control", #onchange = "javascript:DoSomething(this.value);" }
And this doesn't (mind the lowercase 'n' in #name)
new { #id = "myID", #name = "myName", #Value = "myValue", #class = "form-control", #onchange = "javascript:DoSomething(this.value);" }
You can set/change the ID just like any HTML attribute (but not name I've found).
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status, AdminStatusReference.GetAdminStatusOptions(), new { id = string.Format("Status_{0}",index ) });
Just use "Name" instead of "name" and it works.
#Html.DropDownList("ClassID", null, "Select Class", htmlAttributes: new { id = _id, Name =_id, #class = "form-control" })
You need to change From DropDownListFor To DropDownList. Than you can change name easily.
#Html.DropDownList("YourName", SelectList, new { #id = "YourId", #class = "YourClass" })
Hope It will work.
ID can be changed as described by #Arbiter. However, if you want to change the name, then I think you need to use #Html.DropDownList rather than #Html.DropDownListFor. This loses you any benefits of having the strong typing for the property element, but as just changing IDs means you can't access the values in a meaningful way if looking at the Request.Form response, this may be an acceptable workaround for you.
Thanks .. it work...adding .Name change the name of the html password attribute
#Html.PasswordFor(Function(model) model.password, New With {.Autocomplete = "off", .Name = "oldpassword", .id = "oldpassword", .value = Model.password, .readonly = True})
My solution to this issue is to replace the id and name after DropDownListFor() with a html helper extension method.
public static MvcHtmlString ReplaceIdAndName(this MvcHtmlString htmlSource, string name)
{
MvcHtmlString result;
if (name == null)
result = htmlSource;
else
{
string id = name.Replace("[", "_").Replace("]", "_").Replace(".", "_"); // HTML ids cannot have []. so MVC convention replaces with _
XDocument html = XDocument.Parse(htmlSource.ToHtmlString());
html.Elements().Select(e => e.Attribute("id")).FirstOrDefault().SetValue(id);
html.Elements().Select(e => e.Attribute("name")).FirstOrDefault().SetValue(name);
result = MvcHtmlString.Create(html.ToString());
}
return result;
}
DropDownListFor(...).ReplaceIdAndName("myclass[1].myprop");

How to make dropdownlist show a selected value in asp.net mvc?

I have an edit page with a Html.DropDownList in it....I cant show the dropdownlist value it always shows up with Select instead i want to make the dropdown show an item as selected based on a model value say Model.Mes_Id... Any suggestion how it can be done...
<p>
<label for="MeasurementTypeId">MeasurementType:</label>
<%= Html.DropDownList("MeasurementType", // what should i give here?)%>
<%= Html.ValidationMessage("MeasurementTypeId", "*") %>
</p>
EDIT: It has the list items but i want to show a value selected in the edit view...
public ActionResult Edit(int id)
{
var mesurementTypes = consRepository.FindAllMeasurements();
ViewData["MeasurementType"] = mesurementTypes;
var material = consRepository.GetMaterial(id);
return View("Edit", material);
}
My repository method,
public IEnumerable<SelectListItem> FindAllMeasurements()
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name
};
return mesurements;
}
Set the selected item when you create the IEnumerable<SelectListItem>.
Personally I would create a specialized viewmodel for the form but going by your code, do something like:
public ActionResult Edit(int id)
{
//Put this first
var material = consRepository.GetMaterial(id);
//pass in your selected item
var mesurementTypes = consRepository.FindAllMeasurements(material.MeasurementTypeId);
ViewData["MeasurementType"] = mesurementTypes;
return View("Edit", material);
}
Then change your repository method to something like:
public IEnumerable<SelectListItem> FindAllMeasurements(int selectedId)
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name,
Selected = mt.Id == selectedId
};
return mesurements;
}
HTHs,
Charles
Have a look at this blog entry.
http://weblogs.asp.net/ashicmahtab/archive/2009/03/27/asp-net-mvc-html-dropdownlist-and-selected-value.aspx
Basically, you need to convert your mesurementTypes list/enumerable into a SelectList or IEnumerable<SelectListItem>.
I would recommend, if possible, upgrading to ASP.NET MVC2 and using Html.DropDownListFor()
You should be returning a SelectionList which can specify a selected item.
How to create a DropDownList with ASP.NET MVC
Assuming that Model.Mes_Id contais the selected value, you can do something like this
<%
var Measurements = new SelectList((IEnumerable)ViewData["MeasurementType"], "Id", "Name", Model.Mes_Id);
Response.Write(Html.DropDownList("measurement_type", Measurements, "Select"));
%>
Html.DropDownListFor didn't work for me So I got the poppy like this
(in Edit method )
CreatList(long.Parse(wc.ParentID.ToString()));
private void CreatList(long selected= 0)
{
SqlConnection conn = new SqlConnection(Config.ConnectionStringSimple);
conn.Open();
Category wn = new Category(conn);
CategoryCollection coll = new CategoryCollection();
Category.FetchList(conn, ref coll);
ViewBag.ParentID = GetList(coll, selected);
}
private List<SelectListItem> GetList(CategoryCollection coll, long selected)
{
List<SelectListItem> st = new List<SelectListItem>();
foreach (var cat in coll)
{
st.Add( new SelectListItem
{
Text = cat.Name,
Value = cat.ID.ToString(),
Selected = cat.ID == selected
});
}
SelectListItem s = new SelectListItem {
Text = Resources.lblSelect,
Value = "0"
};
st.Insert(0, s);
return st;
}
<div class="editor-label">
#Html.LabelFor(model => model.ParentID)
</div>
<div class="editor-field">
#Html.DropDownList("ddlCat", (List<SelectListItem>)ViewBag.ParentID)
#Html.ValidationMessageFor(model => model.ParentID)
</div>

Resources