DropdownlistFor not getting selected value? - asp.net-mvc

I have a DropdownlistFor that is not getting the value that is chosen in the DDL. I've done some research and tried implementing some of the suggestions I've seen but mine still isn't working.
I'm using an IEnumerable<SelectListItem> as well as a string property to hold that selected value in my view model.
public IEnumerable<SelectListItem> AvailableSeats { get; set; }
public string Seat { get; set; }
I set the Seat property to an initial value when the ViewModel is created.
Seat = "FO";
This is how I'm populating my SelectListItem. "FO" is always an option but they have "CA" I add that to the SelectList as well.
public static List<SelectListItem> GetAvailableSeats(string currentSeat)
{
List<SelectListItem> seats = new List<SelectListItem>();
seats.Add(new SelectListItem { Text = "FO", Value = "FO" });
if (currentSeat.ToUpper() == "CA")
seats.Add(new SelectListItem { Text = "CA", Value = "CA", Selected = true });
return seats;
}
This is my Razor View:
#Html.DropDownListFor(m => m.Seat, Model.AvailableSeats, new { #class = "form-control" })
The HTML that gets produced is:
<select class="form-control" id="Seat" name="Seat">
<option value="FO">FO</option>
<option selected="selected" value="CA">CA</option>
</select>
However, when I select "FO" as my option and then submit my form, the ViewModel still has "CA".

I finally stumbled across the problem after going through this
post.
I'm posting in case it might help someone else. Inside my form I was assigning the the "Seat" property to a hidden field #Html.HiddenFor(m => m.Seat) and I didn't nee to do that. Getting rid of that hidden field fixed the problem.

Related

Unable to set value in dropdownlist

I have a dropdownlist,while editing i need to set the current value.But my codes are not working.
My view look like follow
#Html.DropDownListFor(m => m.id, Model.ddls, "Please Select", new { #class = "form-control" })
Model
public string id { get; set; }
public List<SelectListItem> ddls { get; set; }
Controller
public IActionResult editmaster(string id, string sec)
{
master m = new master();//here is my model
m.ddls = PopulateDDLDataSet(ds.Tables[1], "companyname", "companyid");//ddls is my object and populateddldataset is my methode to fill the list
return View(m);
}
ddls is the selectedlistitems that i have filled from controller,that work fine.But the value which in in id not set on the list
Checked the code and its working for me. Could you provide more details about your model?
Wanted to say that you can make similar things by using built-in razor tag helpers that is more clear.
Documentation for select
Example of using tag helper in your code:
<select class="form-control" asp-for="#Model.id" asp-items="Model.ddls">
<option selected>Please select</option>
</select>
please follow this, it may be this code help you.
Model Code
public class testmdl
{
public string id { get; set; }
public IEnumerable<SelectListItem> ddls { get; set; }
}
Controller Code
//------ without using entity for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
IEnumerable<SelectListItem> companyList = new List<SelectListItem>
{
new SelectListItem { Value = "001", Text = "StackOverflow1" },
new SelectListItem { Value = "002", Text = "StackOverflow2" }
};
obj.ddls =companyList ;
return View(obj);
}
//--- using entity framework for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
List<SelectListItem> companyList = new SelectList(db.yourcompanytable, "companyid", "comapnyname").ToList();
obj.ddls =companyList ;
return View(obj);
}
View Code
<select id="id1" name="id1" asp-for="id" asp-items="#Model.ddls" class="form-control">
<option value=#null>--- Select --- </option>
</select>
<span asp-validation-for="id" style="color:red;"></span>
In my case none of the above answers work(I don't clearly understand what went wrong for me) ,but finally i achieved in an alternative way.Below my codes.Thanks for all the supports.
<script>
document.getElementById("id").value =#Model.id;
</script>
Put this after binding the dropdownlist.

Display dynamic title for dropdown listitem using razor

I have one dropdown in my MVC application.
I have a field in my model:
public IList<SexGenderModel> SexualOrientationList { get; set; }
class for SexGenderModel:
public class SexGenderModel
{
public int? MasterID { get; set; }
public string CodeDescription { get; set; }
public string SNOMED { get; set; }
}
In my view page I have used razor syntax
#Html.DropDownListFor(x => x.SexualOrientationList, new SelectList(Model.SexualOrientationList, "MasterID", "CodeDescription"), "--Select--", new { #class = "form-control input-sm"})
Every list item has their own SNOMED which I want to display in tooltip.
Please note I want to display tooltip for ListItem not for selected item of dropdown.
How can I achieve this with razor?
Any other option to map attributes to dropdownlist(Model.SexualOrientationList) from backend? How?
All you need to add attribute "title" to each item in dropdown
<select>
#foreach (var item in Model.SexualOrientationList)
{
<option title='#item.SNOMED' value="#item.MasterID">#item.CodeDescription</option>
}
</select>
Going further with #Khaled-Yosry 's answer:
#Ankita this DOES use Razor, so I'm not sure why you find yourself restricted.
If it's the <select> tag rendering you are worried about, you can append the necessary tags yourself:
All you need to add attribute "title" to each item in dropdown
<select name="#Html.NameFor(m => m.SexualOrientation)" id="#Html.IdFor(m => m.SexualOrientation)" class="form-control input-sm">
<option value="">--Select one--</option>
#foreach (var item in Model.SexualOrientationList)
{
<option title="#item.SNOMED" value="#item.MasterID" #(Model.SexualOrientation == item.MasterID ? "selected" : string.empty)>#item.CodeDescription</option>
}
</select>
Also, don't forget to include a property in your Model which will actually be bound to the selected value of the dropdown list:
public int SexualOrientation { get; set; }

Get dynamic radio buttons values

I'm doing survey system on asp.net mvc 4. How can i get all radio buttons data in Controller ?
Example
$(document).ready(function(){
var AnswerCounter = 0;
$("#answer-add").click(function(){
var answertext = $("#answer-text").val();
var answerContent = $('<p>', {
class:'external',
});
var inputAnswer = $('<input>',{
id:'answer-'+AnswerCounter,
name:'rb',
class:'answer-radio'
}).attr("type","radio").appendTo(answerContent);
var labelAnswer = $('<label>').attr('for','answer-'+AnswerCounter).text(answertext).appendTo(answerContent);
$('#answers').append(answerContent);
AnswerCounter++;
});
});
You can see in the example buttons created by jquery. so i can use model binding.
Thanks.
The HTML typically geneated for MVC3 radiobuttons look like this
<input name="FeedingTime" id="FeedingTime" type="radio" value="Morning"/>
<input name="FeedingTime" id="FeedingTime" type="radio" value="Afternoon" checked="checked"/>
and when the radio button group posts, it will bind to the variable that matches the name.
[HttpPost]
public ActionResult Index (string FeedingTime){
//feeding time here is "Afternoon"
}
so to make your code bind correctly,
set the value of the input 'value' attribute in your script, and
have a variable in the ActionResult that matches the 'name' attribute in the html input element
EDIT: This answer is no longer relevant to the question being asked.
to get the value from radio buttons you can bind to them like you would a string variable; suppose in your view you have
#Html.LabelFor(m => m.FeedingTime,"Morning")
#Html.RadioButtonFor(m => m.FeedingTime, "Morning")<br />
#Html.LabelFor(m => m.FeedingTime,"Afternoon")
#Html.RadioButtonFor(m => m.FeedingTime, "Afternoon")<br />
#Html.LabelFor(m => m.FeedingTime,"Night")
#Html.RadioButtonFor(m => m.FeedingTime, "Night")
when you post back, you would capture this in a string variable
public ActionResult(..., string FeedingTime, ...){
}
normally this variable is embedded in a viewmodel such as
public class AnimalViewModel
{
public string Name { get; set; }
public string Type { get; set; }
public string FavoriteColor { get; set; }
public string FeedingTime { get; set; }
}
so that when you post
[HttpPost]
public ActionResult Index(AnimalViewModel viewModel){
...
}
it binds the viewmodel to the data automagically.
To answer your question more directly. I dont think theres a way to detect all radiobutton inputs on a page, you can only detect the results from that are posted from the radio button. There is no indication that the string posted was once the answer to a radiobutton. So, if you want to know the values of all radiobuttons on the page, you will simply have to check the values of the strings which are posted.

How set select element's first option value to 0 instead of empty option value?

I want to set first option value to 0 instead leaving it blank. How can I set this?
i.e
<select id="PatentId" name="ParentId">
<option value="0">--Select--</option>
<option value="1">Books</option>
// other options
</select>
My code is as
<div class="editor-field">
#Html.DropDownList("ParentId","--Select--")
#Html.ValidationMessageFor(model => model.ParentId)
</div>
You can't do this with the built-in helper. You will have to write a custom helper or hardcode or whatever.
Or simply use a view model and a nullable integer:
[Required]
public int? ParentId { get; set; }
Now you will no longer have any problems or needs to use 0 as first option.
Also it is better to use the strongly typed version of the helper:
#Html.DropDownListFor(model => model.ParentId, Model.Parents, "--Select--")
But if for some other reason (which I don't see at the moment) you need to use 0 as first option you are on your own in the wilderness.
Finally I found the following code working
private SelectList AddFirstItem(SelectList list)
{
List<SelectListItem> _list = list.ToList();
_list.Insert(0, new SelectListItem() { Value = "0", Text = "--Select--" });
return new SelectList((IEnumerable<SelectListItem>)_list, "Value", "Text", list.SelectedValue);
}
Keep the "Value" and "Text". The Last one list.SelectedValue is to keep selected values as it is.
You can use the above function like
public ActionResult Create()
{
ViewBag.ParentId = AddFirstItem(new SelectList(db.Categories, "Id", "Name"));
return View();
}
It worked.

ASP .Net MVC 3 Html.DropDown not binding to variable

I have a list of Organizations (CalledOrganizationSelectList) and one of them is the one that's being called (CalledOrganizationId). I set both in my ViewModel but MVC / Razor doesn't render the dropdown correctly (ie does not set the selected="selected" attribute for the correct item in the dropdown).
There is a workaround which makes even less sense. I added a new member to my ViewModel and bound the dropdown to that. This works fine. Until just now when it's stopped working...
public class CallViewModel{
public int? CalledOrganizationId { get; set; }
public SelectList CalledOrganizationSelectList { get; set; }}
In my controller:
var vm = new CallViewModel();
var calledOrganizationSelectList = new List<object>();
calledOrganizationSelectList.Add( new {Text="",Id=""});
calledOrganizationSelectList.AddRange(
db.MyOrganizations.OrderBy(x=>x.Name)
.Select(x => new { Text = x.Name, Id = x.Id.ToString()}).ToList());
var sl = new SelectList(calledOrganizationSelectList, "Id", "Text",
vm.CalledOrganizationId);
vm.CalledOrganizationSelectList = sl;
return View(vm);
In my view:
<div>CalledOrganizationId = #Model.CalledOrganizationId :
select list contains
<ul>#foreach (var itm in Model.CalledOrganizationSelectList)
{<li>Value: #itm.Value Text: #itm.Text Is Selected: #itm.Selected</li>}
</ul>
</div>
#Html.DropDownList("CalledOrganizationId", Model.CalledOrganizationSelectList)
In my rendered page source:
<div>CalledOrganizationId = 38 : select list contains
<ul>
<li>Value: Text: Is Selected: False</li>
<li>Value: 37 Text: rrr Is Selected: False</li>
<li>Value: 38 Text: sss1 Is Selected: True</li>
</ul>
</div>
<select data-val="true" data-val-number="The field CalledOrganizationId must be a number." id="CalledOrganizationId" name="CalledOrganizationId">
<option selected="selected" value=""></option>
<option value="37">rrr</option>
<option value="38">sss1</option> </select>
I've worked around it after first pulling out what was left of my hair and then by introducing a new variable on my ViewModel, which seems to work ok.
Having 2 properties on your viewmodel is the correct way to do DropDownLists. One property holds all of the available options, and the other holds the currently selected option:
public class CallViewModel
{
// this captures the selected item
public int? CalledOrganizationId { get; set; }
// this contains the select list options
public IEnumerable<SelectListItem> CalledOrganizationSelectList { get; set; }
}
However, you do not need to add the empty option in the controller. You can do this in the view:
#Html.DropDownListFor(m => m.CalledOrganizationId,
Model.CalledOrganizationSelectList, "")
You can just get away with this in the controller:
var vm = new CallViewModel();
//var calledOrganizationSelectList = new List<object>();
//calledOrganizationSelectList.Add( new {Text="",Id=""});
//calledOrganizationSelectList.AddRange(
//db.MyOrganizations.OrderBy(x=>x.Name)
// .Select(x => new { Text = x.Name, Id = x.Id.ToString()}).ToList());
//var sl = new SelectList(calledOrganizationSelectList, "Id", "Text",
// vm.CalledOrganizationId);
//vm.CalledOrganizationSelectList = sl;
vm.CalledOrganizationSelectList = db.MyOrganizations.OrderBy(x => x.Name)
.Select(x => new SelectListItem
{
Text = x.Name,
//Id = x.Id.ToString() // do not use "Id" for the property name,
Value = x.Id.ToString() // use "Value" -- it is a SelectListItem property
});
// if you want to set the selected item on the dropdownlist, do it here
vm.CalledOrganizationId = 37;
return View(vm);

Resources