#html.dropdownlistfor not showing selected value on binding - c#

i m binding a dropdownlist in asp.net mvc 4 before binding i mark a value as selected but when the view is shown dropdown is binded but selected value is not selected
List<SelectListItem> citylist = new List<SelectListItem>();
var status = (DataSet)_rtmi_repo.GetCity(ref BaseObject);
foreach (DataRow v in status.Tables[0].Rows)
{
if (v["CODE"].ToString() == selectedval)
{
citylist.Add(new SelectListItem { Text = v["CODE"].ToString(), Value = v["CODE"].ToString(), Selected = true });
}
else
{
citylist.Add(new SelectListItem { Text = v["CODE"].ToString(), Value = v["CODE"].ToString() });
}
}
VIEW
#{var ddl = (IEnumerable<SelectListItem>)ViewBag.Location;}
#Html.DropDownListFor(model=>model.Location,ddl , new { #class = "form-control" })
even in ddl it show the selected true but after binding it always selects first value in list as selected
also created the filddle but here it works fine
"Example FIDDLE"

If you have a viewbag name same as the model property name, then the selected option will not be set to the DropDownListFor.

Related

How to make the default value highlighted or focused at the list of dropdownlist

I already got the default value and the value already became the default, but the default value has no highlight or focus in the dropdown list.
I am using SelectItemList function.
Controller:
private List<SelectListItem> SelectWeek() {
using(var db = new UsersContext()) {
int currentYear = DateTime.Now.Year;
selectListItems = db.WorkWeekDetails
.Where(item = >item.YEAR == currentYear).OrderBy(item = >item.WORKWEEK)
.Select(a = >new SelectListItem() {
Text = a.WORKWEEK,
Value = a.WORKWEEK
}).ToList();
selectListItems.Insert(0, new SelectListItem() {
Text = www, //www = "WW13"
Value = www, //www = "WW13"
Selected = true
});
}
return ViewBag.WorkWeek = selectListItems;
}
CSHTML:
#Html.DropDownList("WorkWeek", (List<SelectListItem>)ViewBag.WorkWeek, new { #class = "form-control", required = "required" })
I want "WW13" to be the default value and that value to be highlighted in the dropdown list.
//Example list of dropdownlist :
WW13 // This value will be the default.
ww01
ww02
ww03
ww04
ww05
ww06
ww07
ww08
ww09
ww10
ww11
ww12
ww13 // This value will be highlighted.
ww14
...
Dropdown list:
[
As #Aarif said you can use jquery to hightlight the selected option... something like this
Also I think you should probably pass your drop down list through a View model rather than a viewbag
window.onload = function() {
highlightSelected()
};
function highLightSelected(){
var model = #Html.Raw(Json.Encode(ViewBag.WorkWeek));
foreach(var item in model){
if(item.selected == true){
$("#mydropdownlist").val(item.value);
$("#mydropdownlist").addClass('active');
}
}
}
The syntax might not be exact but the idea is to check your list of SelectedListItem to find the one that is selected and set the drop list's value to that and also add the class which will highlight the selected value, but remember to remove this class on change of the dropdownlist value

Telerik Grid Custom Dropdown doesn't take value

I am having a problem setting up my Telerik KendoUI Grid for Asp.net MVC.
Inside my grid I have linked up a custom kendo DropDownList.
The list looks like this:
#(Html.Kendo().DropDownList()
.BindTo(new List<SelectListItem>() {
new SelectListItem()
{
Text = "A",
Value = "Anrufen"
},
new SelectListItem()
{
Text = "BT",
Value = "nächster Beratungstermin"
},
new SelectListItem()
{
Text = "PT",
Value = "Probetraining"
},
new SelectListItem()
{
Text = "V",
Value = "Verloren"
}
})
.DataValueField("Value")
.DataTextField("Text")
.Name("Ergebnis")
)
I bound it to the Telerik Grid Column like that:
columns.Bound(product => product.Aktion).EditorTemplateName("AktionTemplate").Title("Ergebnis");
Everythin works fine and the DropDown list gets displayed except that the grid doesn't take the value from the selected list element.
When I select anything from the dropdown and trying to save it, then there is no value, it is null.
EDIT:
Controller/Action:
public ActionResult Details(int id)
{
KundeContext kundeContext = new KundeContext();
var result = kundeContext.Kundes.Where(x => x.KdNr == id).FirstOrDefault();
return View(result);
}
Calling Method(AngularJS):
$scope.Select = function (x) {
window.location = "http://localhost:50380/Kunde/Details/" + x;
}
From Documentation on Editor Templates.
The name of the widget should be the same as the name of the property.
Try changing the Name property of your dropdownlist to 'Aktion' instead of 'Ergebnis'.

C# MVC ASP.NET DropDownListFor

I would like to send the selected dropdown option into model.Feit
Assuming, i need DropDownListFor, then select table, then the dropdown..?
//here's my drop down menu in my controller
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Owner", Value = "0", Selected = true });
items.Add(new SelectListItem { Text = "Leader", Value = "1" });
ViewBag.items = items;
//this works fine, but the selected option has to be inserted into my database when submitted
//the first line shows the label
<div class="editor-label">#Html.LabelFor(model => model.Feit)</div>
//the second line needs to show as a dropdownlist with the 2 options above here
<div class="editor-field">#Html.DropDownListFor(model => model.Feit, "items")</div>
//when the option is selected, and submit is pressed this has to be sent to the db
// this works for all other fields, but my syntax is wrong at , "items"
Since you've already populated an IEnumerable<SelectListItem> in your viewbag, you just need to access it and cast it to ensure the correct DropDownListFor overload is used:
#Html.DropDownListFor(model => model.Feit, (IEnumerable<SelectListItem>)ViewBag.items)
model.Feit should be of type int or something that can hold the value of the selected item.
Use this
#Html.DropDownListFor(m => m.Feit, new SelectList(ViewBag.items, "Id","Name"),"Select")

DropDownList selected value on a razor view page

I have the following DropDownList on a View Layout page that displays languages from an SQL database. I want the selected item of the dropdownlist to be the page current culture (originalCulture). How can I accomplish that?
For example if the page current culture (originalCulture="en") is equal to (item.language_UI="en") then the DDL selected item should be English (item.language). I know that it's easy but I'm not familiar with Razor codes. Can someone help?
#{
var db = Database.Open("DefaultConnection");
var listLanguage = "SELECT language, language_UI FROM Languages";
var originalCulture = Convert.ToString(System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName);
List<SelectListItem> languagedropdownlistdata = new List<SelectListItem>();
bool isSelected = false;
foreach (var item in db.Query(listLanguage))
{
languagedropdownlistdata.Add(new SelectListItem
{
Text = item.language,
Value = item.language_UI,
Selected = isSelected
});
}
}
And here is the DropDownList on the content page:
#Html.DropDownList("lang", languagedropdownlistdata
<input type="submit" value="Select" />
It is not really the "Razor" codes. It is mostly C# :)
Your isSelected variable seems to be false always.
You need to change your loop body to the following:
foreach (var item in db.Query(listLanguage))
{
languagedropdownlistdata.Add(new SelectListItem
{
Text = item.language,
Value = item.language_UI,
Selected = (item.language_UI == originalCulture)
});
}
The statement (item.language_UI == originalCulture) would be true only if the language_UI propery will contain exactly the same string as originalCulture, therefore your code should work properly.

DropDownList in MVC?

I am having a dropdownlist in my appliaction which I have binded through the database records
but on any of the edit form I want to set the selected index of the dropdown list how shall I do that ,I am Pastng my code here.
Code for binding the dropdownlist
public IList GetFeedbackList()
{
int feedbackId = 0;
string feedbackName = string.Empty;
using (var db = new brandconnectionsEntities())
{
return (IList )(from s in db.BC_FeedbackBy
select new
{
feedbackId =s.FeedbackById ,
feedbackName=s.FeedbackBy ,
})
.ToList ();
}
}
//Code for returning the list
IList allfeedbacks = _dropdownProvider.GetFeedbackList();
ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName");
//In the View Page
<%=Html.DropDownList("feedback_for", ViewData["feedback_for"] as SelectList, "--Select--", new { #class = "inputtext1" })%>
Please tell how shall I set the selected index from database
Thanks
Ritz
In the constructor for your select list you can specify the selected item....
ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName",
allfeedbacks.FirstOrDefault(f => f.FeedbackById == {ID of selected record}));
Pass a List of SelectListItems to the View. SelectListItem has a property selected.
IEnumerable<SelectListItem> itemList =
from item in Items
select new SelectListItem
{
Text = item.Name,
Value = item.Key,
Selected = ( item.Key == "TheKeyYouWantToSet")
};
ViewData["feedback_for"] = new SelectList(allfeedbacks, "feedbackId", "feedbackName", selectedvalue);
At least in MVC2.
I had a problem which disappeared when I gave the dropdown the same name as the key. Ie:
<%=Html.DropDownList("feedbackId", ViewData["feedback_for"] as SelectList, "--Select--", new { #class = "inputtext1" })%>

Categories