selecting an option in html.dropdown helper method using boolean result - asp.net-mvc

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?

Related

Retain Value on editing drop down on Razor

Want to reduce my logic on View data from drop down won't come from data base.
Current code
#Html.DropDownListFor(m => m.MyViewModel.Value,
new List<SelectListItem> {
new SelectListItem { Text = "1",Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" },
new SelectListItem { Text = "4", Value = "4" },
new SelectListItem { Text = "5", Value = "5" },
});
Trying to achieve
<select id="MyViewModel.name" name="MyViewModel.name">
<option value="">--Select--</option>
#for (int i = 1; i <= 5; i++)
{
<option value="#i">#i</option>
}
</select>
On submitting the form I am getting the selected value in my ViewModel i.e action but on editing am not the selected value Like
<select data-val="true" id="ddl" name="">
<option value="1">1</option>
<option value="2">2</option>
**<option selected="selected" value="3">3</option>**
<option value="4">4</option>
<option value="5">5</option>
</select>
You code for generating the SelectList can be simplified to
#Html.DropDownListFor(m => m.yourProperty, new SelectList(new List<int> { 1, 2, 3, 4, 5 }))
However, that code belongs in the controller, not the view, and ideally you should have a view model with property IEnumerable<SelectListItem>, for example
public class MyViewModel
{
[Required(ErrorMessage = "...."]
[Display(Name = "....")]
public int? SelectedItem { get; set; } // nullable to protect against under-posting attacks
public IEnumerable<SelectListItem> Options { get; set; }
....
}
and in the GET method
MyViewModel model = new MyViewModel
{
Options = new SelectList(new List<int> { 1, 2, 3, 4, 5 })
};
return View(model);
and in the view
Html.DropDownListFor(m => m.SelectedItem, Model.Options, "Please select")
it will be best to define the data at the control level than in Razor
so create and edit actions will return a list which will be used in DropDownListFor
but Edit will also set the selected value

How to save selected value in dropdownlist in MVC-4 after submit?

How to save chosen value in dropdownlist after submit. So the value that you choose in dropdownlist stays after user click on submit.
In my controller I did this:
List<SelectListItem> uraList = new List<SelectListItem>();
for (int i = 1; i < 7; i++)
{
uraList.Add(new SelectListItem
{
Value = i + ":00",
Text = i + ":00"
});
}
ViewBag.IzberiUro = uraList;
ViewBag.IzbranaUra = model.Ura;
In my Model (I think that here is mistake):
public string Ura { get; set; }
And in View I have:
#Html.DropDownList("Ura", ((IEnumerable<SelectListItem>)ViewBag.IzberiUro).Select(t => new SelectListItem() {Text = t.Text, Value = t.Text,Selected = (t.Text == ViewBag.IzbranaUra)}), new {#class = "css"})
The result is, in view I have dropdownlist with values from 1:00 to 6:00 (whitch is correct, and first choosen value is 1:00), but, when I choose e.g. 4:00 and click on submit, the value in dropdown returns to 1:00.
Realy thanks for help.
my generated HTML is then like this:
<select class="form-control" id="Ura" name="Ura" placeholder="Ura" style="width: 100px;">
<option value="1:00">1:00</option>
<option value="2:00">2:00</option>
<option value="3:00">3:00</option>
<option value="4:00">4:00</option>
<option value="5:00">5:00</option>
<option value="6:00">6:00</option>
</select>
Use DropDownListFor instead of DropDownList
#Html.DropDownListFor(m => m.Ura, Model.uraList)

mvc razor dropdown list

I want to know how to put drop down list like this:
<div>
<label>Price Range</label>
<select>
<option value="1">min</option>
<option value="50000">50,000</option>
<option value="100000">100,000</option>
<option value="150000">150,000</option>
</select>
in the view , and read the selected parameter in the controller
tnx
There are many ways to make it work.
Its depend on your needs.
I am going to show you the simplest way to create it in the view itself
You can do it like this all inlined in your *.cshtml file like so:
#{
var loadListItems = new List<SelectListItem>();
loadListItems.Add(new SelectListItem { Text = "text1", Value = "value1", Selected = true });
loadListItems.Add(new SelectListItem { Text = "text2", Value = "value2" });
}
//Begin Form
#Html.DropDownList("ListKey",loadListItems);
//End Form
Will produce the result as follows:
<select name="ListKey">
<option value="value1">text1</option>
<option value="value2">text2</option>
</select>
And on submitting it on controller side you can get the values as follows:
ActionResult YourActionName(FormCollection collection){
var selectedValue = collection["ListKey"];
}

Set selected value of a dropdown in Razor view

I am trying to set the selected value in a dropdown in a razor view.
<select id="drpStatus" name="status">
<option value="A">Active</option>
<option value="S">Suspended</option>
<option value="T">Terminated</option>
<option value="D">Deleted</option>
</select>
//I am trying with the below code, based on the value in Model, I want to set the particular option as selected
<option selected=#{if(#Model!=null && #Model.Status=='A'){'selected'}} value="A">Active</option>
Above code is not working, please let me know if I am working in a right direction or is there any other/better way to achieve it.
Try this from your controller
Controller :
var record = db.Records.Find(id);
ViewBag.DropStatus = new SelectList(ListOfStatus, record.Status);
The first parameter for SelectList should be an IEnumerable which will serve as the data source for your DropDownList, the second parameter is for the selected value, so just pass the status property of the record you want to edit.
View:
#Html.DropDownList("Status", string.Empty)
The first parameter is the name of the ViewBag we assigned in the controller, it will also serve as the name when you post the data. Hope I've made myself clear.
The following is one of some possible solutions
#{
ViewBag.Title = "Index";
Func<char, MvcHtmlString> function = (c) => Model != null && Model.Status == c
? MvcHtmlString.Create("selected='selected'")
: MvcHtmlString.Empty;
}
<h2>Index</h2>
<select id="drpStatus" name="status">
<option #function('A') value="A">Active</option>
<option #function('S') value="S">Suspended</option>
<option #function('T') value="T">Terminated</option>
<option #function('D') value="D">Deleted</option>
</select>
It would be better to use SelectList in your ViewModel.
Another possible solution is using Razor's helper tag in the cshtml:
#helper SetGender(string dropdownvalue)
{
var selected = string.Format("value=\"{0}\"", dropdownvalue);
if ((string.IsNullOrEmpty(dropdownvalue) && string.IsNullOrEmpty(User.GetClaim(ClaimTypes.Gender.ToString()))) ||
(User.GetClaim(ClaimTypes.Gender.ToString()) == dropdownvalue))
{
selected = string.Concat("selected='selected' ", selected);
}
#Html.Raw(selected);
}
<select name="gender">
<option #SetGender("") >-not set-</option>
<option #SetGender("male") >male</option>
<option #SetGender("female") >female</option>
</select>
#{
List<SelectListItem> lstOrderTypes = new List<SelectListItem>();
lstOrderTypes.Add(new SelectListItem {Value = "1", Text = "plan1" });
lstOrderTypes.Add(new SelectListItem {Value = "2", Text = "plan2" });
}
#functions {
public static string GetString(IHtmlContent content)
{
var writer = new System.IO.StringWriter();
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
#{
var x = GetString(Html.DisplayFor(model => model.OrderType));
}
<select>
#foreach (SelectListItem option in lstOrderTypes)
{
<option value="#option.Value" selected="#(option.Value == x)">#option.Text</option>
}
</select>

Handling onchange event in HTML.DropDownList Razor 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");

Resources