Reputation: 547
I have a select tag with several options and each of the options are designated a value.
<select id="dropdown">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
Additionally, I have the following JQuery script.
$(function() {
$(#dropdown).change(function() {
var option = $(this).find("option:selected").text();
var optionValue = $(this).val();
I've checked both values using an 'alert' and they're correct. Now I want to pass these values from the view to the controller. I put the select tag within a form and tried using '.submit()' on both values, but that causes the script to crash. I'm not sure if I'm using '.submit()' correctly, as I'm a beginner in JavaScript and Jquery. So in short, how can I get the option tag value into a method of my controller?
EDIT 1
The select tags are in a form, and I've been trying to submit like this:
$(this).val().submit()
EDIT 2
Additionally, here is the controller method I'm trying to get the value into.
[HttpPost]
public ActionResult Index(string dropdown)
{
string value = dropdown;
//--- conditional logic ---
return View()
}
Upvotes: 0
Views: 9534
Reputation: 641
Best way would be to expand on this.... :) hope it helps.
Model
public class Model
{
public int Id { get; set; }
public IEnumerable<Items> items { get; set; }
}
View
@model App.Models.Model
@using (Html.BeginForm("ActionName", "ControllerName")) {
@Html.DropDownListFor(x => x.Id, Model.Items)
<button type="submit" class="btn btn-info"><i class="fa fa-floppy-o"></i></button>
}
Controller
public ActionResult ActionName(Model model)
{
var blah = model.items;
return View(model);
}
Upvotes: 0
Reputation: 306
You can use ajax to do this kind of task
var dropDownVal = $("#dropdown").val();
$(#dropdown).change(function() {
$.ajax({
url : yourControllerUrl/MyAction,
type: "POST",
data : {
dropDown : dropDownVal
}
});
});
In controller use params and get the value with "dropDown" as key
Upvotes: 0
Reputation: 6538
To use submit()
your dropdown must be in a <form>
<form method="POST" action="yourControllerUrl/MyAction">
<select id="dropdown" name="dropdownName">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</form>
And in the controller :
public ActionResult MyAction(string dropdownName)
{
// use your dropdown value here
}
Upvotes: 1