I currently have the following code in one of my Razor view in an MVC project: <b>Item Code: </b>#Html.DropDownList("ItemID", (SelectList)ViewBag.Items)
I would like to access the value of the drop down list later in an #Ajax.ActionLink in the Razor view. Is there a way to access the value of the drop down list in the view?
Use JQuery to get the current selected value -
$('#dropDownId').val();
If you don't have a special library (like jQuery) to deal with your DOM elements, you can use vanilla Javascript as per the following example:
//get the element by its ID value
var dropdownElement = document.getElementById("ddlItems");
// now we have a reference to the dropdown field, let's read the selected value (or text):
// 1- selected value
var selectedValue = dropdownElement.options[dropdownElement.selectedIndex].value;
// 2- selected text
var selectedText = dropdownElement.options[dropdownElement.selectedIndex].text;
// display a popup with selected text and value
window.alert("selected value is: (" + selectedValue + "), and selected text is: (" + selectedText + ").");
<select id="ddlItems">
<option value="1">1st item</option>
<option value="2">2nd item</option>
<option value="3" selected="selected">3rd item</option>
</select>
If I understand your problem correctly, you're attempting to pass selected value from DropDownList helper into #Ajax.ActionLink helper from the view, which is impossible because #Ajax.ActionLink helper processed and rendered server-side before sending to browser.
You can use #Html.ActionLink helper without routeValues parameter instead and set id attribute of that anchor tag:
#Html.ActionLink("Get Item", "TargetAction", "TargetController", null, new { id = "link" })
Then use unobtrusive AJAX to handle click event of that link and pass selected value from dropdown element there:
$('#link').click(function(e) {
e.preventDefault();
// get selected value from dropdownlist
var selected = $('#ItemID').val();
$.ajax({
type: 'GET',
url: this.href,
data: { id: selected }, // action parameter with selected value
cache: false, // disable caching
success: function (result) {
// do something to target DOM
}
});
return false;
});
Additional notes:
1) Make sure that parameter(s) passed into data setting matches exactly with parameter(s) in the target controller action pointed by href attribute of the link.
public ActionResult TargetAction(int id)
{
// do something
}
2) You can use strongly-typed version of DropDownList, i.e. DropDownListFor to bind viewmodel property.
#Html.DropDownListFor(model => model.ItemID, ViewBag.Items as SelectList, ...)
Related
So im trying to do a dynamic drop down that when a type of sorting is chosen the products get sorted in the controller and the page gets reloaded with the sorted database items
This is my HTML :
<div class="sorting">
<select>
<option value="1">Default sorting</option>
<option value="1">Price low to high</option>
<option value="1">Price high to low</option>
</select>
</div>
And this is my product controller with the action :
public IActionResult Index(string category)
{
IndexVM model = new IndexVM();
model.products = productRepository.getProducts(category);
model.categoryType = category;
model.allItemsCount = model.products.Count;
model.raceChipsCount = productRepository.getCategoryItemsCount("Chip tuning");
model.carInteriorCount = productRepository.getCategoryItemsCount("Car interior");
model.ExhaustSystemsCount = productRepository.getCategoryItemsCount("Exhaust system");
model.gearBoxesCount = productRepository.getCategoryItemsCount("Gear boxes");
model.enginePartsCount = productRepository.getCategoryItemsCount("Engine parts");
return View(model);
}
Basicly all i want is when a type of sorting is chosen to dynamicly redirect me to the Index action without pressing any submit button or anything. Im sorry if the code that i post is not so correct.
$("#myDropdown").change(function () {
$.ajax({
url: [your url to action],
data: { category: this.value },
success: function (data) {
$('#ResultsDiv').html(data);
}
});
});
Let's make some assumptions:
Place id="myDropdown" to your select
Each option must have a different value (now they all have "1")
You must have a div with id = "ResultsDiv" inside of which you will load the ajax response.
Your must return a partial view with the necessary text fields to display your results.
There are different properties for 3 (x,y,z) properties in my database.
I created a dropdown and according to the selection I will make in the dropdown, I want to bring the properties belonging to this property in the database with another dropdown.
(For example I have x, y,z properties. X has ( a,b) , y has (c,d) , z has ( e,f) properties. When I choose the x property in dropdown I want to see a and b properties in the next dropdown. If I choose y property, c and d properties will show up in the next dropdown.)
Beginning of My Code
<form id="CareModal">
#Html.HiddenFor(model => model.PersonID)
#Html.Hidden("DoesAddictionExist", false)
#Html.DropDownList("AddictionStatusID", (IEnumerable<SelectListItem>)ViewBag.AddictionStatus, null, new { #class = "form-control", #onchange = "AddictionChanged(this.value)" })
</form>
Someone said I should use Ajax but I don't know how.
Wherever you want the second dropdown to be put:
<select class="form-control" data-val="true" id="AN ID" name="A NAME (NOT NEEDED)"></select>
In your AddictionChanged method, make an ajax call to the controller.
Something like:
var json = '{dropdownId: ' + //Value passed into function + '}';
$.ajax({
url: '#Url.Action("// Method", "// Controller")',
type:'POST',
data: json,
success: function(result){
// Do whatever
//Create a markup for a select
var markup = "<option Value='0'>Select option</option>";
//Populate the markup
for (var i = 0; i < result.length; i++) {
markup += "<option Value=" + result[i].Value + ">" + result[i].Text + "</option>";
}
//Populate dropdown with value
$("#//DROPDOWNLIST ID").html(markup).show();
}
});
So this calls the controller (that has the parameter dropdownId), passes it an id (whatever you are passing to this function). You, in your controller, would call a service/ db (Not sure how you project is structured) and return a list to this ajax/js function. The code inside the success creates the markup and inserts it inside a dropdown.
I have a list View as:
#foreach(var item in model )
and it has some field as:
#html.DisplayFor(modelItem =>item.prodname ,new{#class="pn"})
I wanted to select a value of this prodname in jquery.
For this I have tried the following process but it doesn't give the required output.
$("#convt").click(function () {
$.each(item, function () {
var snm = (this,'.pn').val().trim();
});
alert(snm);
});
What correction do I need to select a value of this prodname in jquery?
$(".class-name").text() should work, to get the text of element using class name.
I have the following declaration in Razor:
#Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>, ViewBag.CurrentUserRole as string, new { #class = "form-control" }), and it results in a drop-down that looks as follows on page load:
And when I click on the dropdown arrow, I see:
So basically, the User Role is duplicated. How can I change this so that instead of making a new duplicate element, it defaults to the element it is supposed to be? Basically, since ViewBag.RolesEdit is a list, and ViewBag.CurrentUserRole is guaranteed to have an element that is equal to exactly one item in the afformentioned list, how can I loop through the list to compare each other and set the default?
Thank You.
When using Html.DropDownList helper method, To set one option to be pre selected, you just need to set the value of that option to the the ViewBag dictionary with the same key used to generate the SELECT element.
#Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>)
Assuming your action method is setting ViewBag.SelectedRole to the value of the option you want to select.
ViewBag.RolesEdit= new List<SelectListItem>{
new SelectListItem { Value="Administrator", Text="Administrator"},
new SelectListItem { Value="Employees", Text="Employees"},
new SelectListItem { Value="RegularUser", Text="Regular User"},
}
ViewBag.SelectedRole ="RegularUser";
return View();
If you prefer to use Html.DropDownListFor helper method with a strongly typed view and view model, you can follow this post
What is the best ways to bind #Html.DropDownListFor in ASP.NET MVC5?
I am having some difficulty figuring out how to return the selected item in my HTML.DropDownList so that upon hitting a submit button, the selected item text will be looked up in my database. Here is what I have:
#{
var selectStaff = "Select LastName + ', ' + FirstName AS Name, StaffID From StaffList ORDER BY LastName";
var data = db.Query(selectStaff);
var items = data.Select(i => new SelectListItem {
Text = i.Name
});
}
And then in the html..
#Html.DropDownList("Select1", items)
This works fine, as my dropdownlist is appearing and is populated, but now upon hitting a submit button, I want to be able to search that text of the selected item in my database. How would I go about doing this?
If you don't bind the dropdown to a property on your view model (which would be preferable), you can still get it simply using Request.Form["Select1"] in your controller action.
If you mean that you want to be able to get the value while still on the razor page, you need to use jQuery (or other javascript) to get the value.
To get the value with jQuery:
$(document).ready(function () {
$("#YourSubmitButtonID").click(function () {
// Get the value from 'Select1'
var value = $("#Select1").val();
});
});
To do something with the value, you would have to use an ajax function, something like this:
$.ajax({
url: '#Url.Action("ActionName", "ControllerName")',
data: { valueToQuery: $("#Select1").val() },
success: function (data) {
// The data is the result
}
});
On the controller named ControllerName in this example, you'd have the code that queries the database and returns your result.
public ActionResult ActionName(string valueToQuery)
{
// Do your stuff here
return Json("your result", , JsonRequestBehavior.AllowGet);
{
I have also found THIS very interesting that May help you out!
You may also try the following Steps if you don't want to use Ajax or Json tactics:
var sql = "SELECT ProductId, ProductName FROM Products";
var data = Database.Open("Northwind").Query(sql);
var items = data.Select(i => new SelectListItem {
Value = i.ProductId.ToString(),
Text = i.ProductName
});
#Html.DropDownList("productid", items)
And Also:
var sql = "SELECT ProductId, ProductName FROM Products";
var data = Database.Open("Northwind").Query(sql);
<select name="productid">
#foreach(var row in data){
<option value="#row.ProductId">#row.ProductName</option>
}
</select>