I have a list:
public IList<SelectListItem> ToCountryList { get; set; }
I have this line in the razor view:
#Html.DropDownListFor(m => m.Filter.ToCountryId, Model.ToCountryList, string.Empty, new { style = "min-width: 100px; width:180px" })
Now I want jQuery to select ToCountryId from the selected value of the dropdownlist.
I need the id of the record. For example - I have a pair: ID-NAME 5-USA. So I need to retrieve 5 (int)
How should I get the id?
This gives nothing:
$("select[name='Filter.ToCountryId'] option:selected").val()
HTML from browser (not sure how to publish - so plain text):
..select starts
select id="Filter_ToCountryId" name="Filter.ToCountryId" style="min-width: 100px; width:180px"
option tags with countries
..select ends
Just give your dropdown a deterministic id:
#Html.DropDownListFor(
m => m.Filter.ToCountryId,
Model.ToCountryList,
string.Empty,
new { id = "myddl", style = "min-width: 100px; width:180px" }
)
and then you could easily get the selected value using an id selector:
$('#myddl').val()
You should take value from the select itself, not from the option:
$("select[name='Filter.ToCountryId']").val()
Related
I am doing the CRUD for the table called Recipe. The whole functionality is already created in an API and at this point, I am trying to implement it on a web page. During the creation of a new recipe, you have to complete some fields such as TotalTimeUnitId. This is a column in the Recipe table that only takes integers; however, in the user interface you have to pick from a list with seconds/minutes/hours, their value being the thing that needs to be passed in the database through the controller.
<div class="form-group">
#Html.LabelFor(model => model.TotalTimeUnitId)
#Html.EditorFor(model => model.TotalTimeUnitId)
#Html.ValidationMessageFor(model => model.TotalTimeUnitId)
<select id="list" onchange="getSelectedtValue();">
<option value="1">seconds</option>
<option value="2">minutes</option>
<option value="3">hours</option>
</select>
<script>
function getSelectedtValue() {
var selectedValue = document.getElementById("list").value;
console.log(selectedValue);
}
getSelectedtValue();
</script>
This is the code that I wrote trying to achieve this. If you pick, let's say, minutes from the list, the getSelectedValue() function returns "2". How can I be able to call this method inside the EditorFor so the variable TotalTimeUnitId will be assigned the value? Is there another way to doing this?
#Html.DropDownListFor(
model => model.TotalTimeUnitId,
new SelectList(
new List<Object>{
new { value = 1 , text = "Seconds" },
new { value = 2 , text = "Minutes" },
new { value = 3 , text = "Hours"}
},
"value",
"text",
Model.TotalTimeUnitId
)
)
This did the job.
I'm trying to deal with radiobutton ids in asp MVC 5
I'm working like this
Example model
class A
{
public bool? radio { get; set; }
}
and in razor view
#Html.RadioButtonFor(x => x.NeutroBT, Model.NeutroBT, new { #id = "True"})
#Html.RadioButtonFor(x => x.NeutroBT, !Model.NeutroBT, new { #id = "False})
It doesn't cause problem, but I'm working in an editortemplate, and I want it to have generated id, to access in some way like #Html.IdFor(x => x.NeutroBT, true) and #Html.IdFor(x => x.NeutroBT, false) from the other views, just preventing changes in the future
Is some like this possible? I pass a lot of time searching and I didn't get anything similar
If is not possible, what is the best way to deal with it?
thanks!
There is no need to use an id attribute. Instead you can just use the name attribute to select or set the value via javascript (and in any case, #Html.IdFor() will only ever returnNeutroBT, not theidthat you override in theRadioButtonFor()` method so it cannot be used in your case)
In addition, the 2nd parameter of RadioButtonFor() should be true or false (not Model.NeutroBT and !Model.NeutroBT).
And to associate a label with the button, you can wrap it in a <label>, for example
<label>
#Html.RadioButtonFor(x => x.NeutroBT, true, new { id = ""})
<span>Yes</span>
</label>
<label>
#Html.RadioButtonFor(x => x.NeutroBT, false, new { id = ""})
<span>No</span>
</label>
Note that new { id = "" } removes the id attribute and prevents invalid html due to duplicate id attributes.
Then to access the selected value using jQuery
var selectedValue = $('input[name="' + #Html.NameFor(x => x.NeutroBT) + '"]:checked').val();
I am trying to develop a web application which I Need to save firm name username and password.
When I try to add firm username and password it gives me same firm ID in the database as;
Firmname : YAHOO INC
UserName : asd
Password : pass
İn formload all firms come but when ı try to save firmname, username and pass it gives me same firmname for all user save.
Any advice how I can resolve such issue?
Here is a simple example of how to create a drop down list in ASP.NET MVC using Html.DropDownListFor.
You can do it like this all inlined in your *.cshtml file like so:
#Html.DropDownListFor(model => model.Package.State, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
2))
With produces this:
<select id="Package_State" name="Package.State"><option value="0">Red</option>
<option value="1">Blue</option>
<option value="2">Green</option>
</select>
The model => model.Package.State expression is used to generate the id and name on the select.
The string value and text matter as they need to match the model attributes of the listItem in the list.
Or you can create your own List collection (with different fields for value and text) in your controller, set it on you model, and then use in your view like this:
#Html.DropDownListFor(model => model.Package.State.Id, new SelectList(
Model.PackageStates,
"id",
"name",
Model.Package.State.Id))
I have many DropDownLists on page
class BigViewModel
{
public List<SmallViewModel> SmallVM {get;set;}
public List<SelectListItem> Items {get;set;}
//some other properties
}
class SmallViewModel
{
public string ItemId {get;set;}
//some other properties
}
<table>
#for( var i = 0;i<Model.SmallVM.Count();i++)
{
<tr>
<td>
#Html.DropdownListFor(m=> m.SmallVM.ItemId, Model.Items)
</td>
</tr>
}
//display other properties
</table>
in controller
bigViewModel.Items = List<SelectListItem>
{
new SelectListItem{Value = "1", Text = "aaa"},
new SelectListItem{Value = "2", Text = "bbb"},
new SelectListItem{Value = "3", Text = "ccc"},
}
bigViewModel.SmallVM = new List<SmallViewModel>
{
new SmallViewModel{ItemId = 3},
new SmallViewModel{ItemId = 2},
}
In controller I set diffrent ItemId for every SmallVM and each DropDownList uses the same Items collection. I want to set default Value from SmallViewModel for each DropDownList. For example in this case there are two DropDownLists first should display default text "ccc" and second "bbb".
Should I put diffrent List<SelectedListItem> for every SmallViewModel and set them Selected property or there is other way?
This behavior has been reported as a bug on CodePlex but not yet fixed. Using DropDownListFor() in a for loop does not bind correctly and the first option is always selected despite the value of the property. In order for DropDownListFor() to work correctly when using a collection, you need to use an EditorTemplate for the model.
In /Views/Shared/EditorTemplates/SmallViewModel.cshtml
#model SmallViewModel
#Html.DropdownListFor(m => m.ItemId, (SelectList)ViewData["Items"])
Then in the main view
#model BigViewModel
#using(Html.BeginForm())
{
// Pass the select list to the EditorTemplate as addtionalViewData
#Html.EditorFor(m => m.SmallVM, new { Items = Model.Items })
<input type="submit" />
}
You should now have 2 <select> controls displaying "ccc" and "bbb" respectively.
Based on your code updates, I think you just need to modify your view code to:
#Html.DropdownListFor(m=> m.SmallVM[i].ItemId, Model.Items)
However, I have distinct feeling that this is very much an XY problem, and although this change will make everything wire up on post, you're still not going to be getting what you actually need for the true problem you're trying to solve.
Controller
public void setViewBags()
{
List<GroepModel> groepen = Mapper.Map<List<GroepenWerkvorm>, List<GroepModel>>(db.GroepenWerkvorms.ToList());
var groepmodel = new DropDownModel();
groepmodel.list = new SelectList(groepen, "id", "Naam");
ViewBag.groepmodel = groepmodel;
}
View:
#Html.DropDownListFor(model => model.selectedItem, ViewBag.groepmodel.list as IEnumerable<SelectListItem>,"Selecteer een groep", new { #class = "groepen" })
Each of my elements in groepen has a property called description. I'd like to set the title of each element in the dropdown to the according description, so the user can hover over them to see the description.
I'm assuming I'd probably need JQuery to do this?
var i = 0;
$('.groepen option').each(function(){
$(this).attr('title',// Get the correct description somehow?)
i++;
});
I'm guessing this would probably work, but how do I get the correct description for each element?
The DropDownListFor helper has no support for setting additional attributes on the generated option elements. If you need to set something like a title attribute, you'll need to generate your options manually:
<select id="#Html.IdFor(m => m.selectedItem)" name="#Html.NameFor(m => m.selectedItem)">
#foreach (var groepModel in groepen)
{
<option value="#groepModel.id" title="#groepModel.Description">#groepModel.Naam</option>
}
</select>