Reputation: 516
This is my code Display data from the database into DropDownList in asp.net MVC3 In this I can now display data from database into dropdownlist but now I want that if I select any thing from dropdownlist data I want that selected value pass in my stored procedure. I know there is same question might be available or has already been asked but I am not getting my answer which I want. If anyone can explain me step by step or provide me some useful links.
Upvotes: 0
Views: 3057
Reputation: 5545
This code is not completly tested and implemented.
You can acheive it using onchange
event of dropdownlist
.
@Html.DropDownListFor(x => x.SelectedItemValue,new {@onchange="passvalue(this);"})
Handle it using javascript and ajax
<script type="text/javascript">
function passvalue(e){
$.ajax({
type: 'POST',
dataType: 'json',
url: '@Url.Action("Index", "Home")',
data: ({ selectedValue: e.innerHTML }),
success: function (result) {
},
error: function (result) {
alert('error');
}
});
}
</script>
Now you can get the selected value to the controller
[HttpPost]
public ActionResult Index(int selectedValue)
{
// do whatever you want with `selectedValue`
}
Hope it helps
Upvotes: 1
Reputation: 8147
There are several approaches. One of the simplest is to have a ViewModel with a collection of SelectListItems to render in the drop-down and an item to take the selection. In my example code below of course I am using hard-coded values etc to demo the point!
ViewModel
public class TestViewModel
{
public IEnumerable<SelectListItem> TestListItems
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "Item 1", Value = "1" },
new SelectListItem { Text = "Item 1", Value = "1" },
new SelectListItem { Text = "Item 1", Value = "1" },
};
}
}
public string SelectedItemValue { get; set; }
}
View
<p>@Html.DropDownListFor(x => x.SelectedItemValue, new SelectList(Model.TestListItems, "Value", "Text"))</p>
Controller
public ActionResult Index()
{
var viewModel = new TestViewModel();
return View(viewModel);
}
[HttpPost]
public ActionResult Index(TestViewModel viewModel)
{
string youChose = viewModel.SelectedItemValue;
// ...
}
Also, to highlight the collection doesn't have to be of SelectListItem
and could be another type. Then all you would need to do is change your view to perform a .Select
to convert into a SelectListItem
. For simplicity I've just made the ViewModel use it directly.
Upvotes: 0
Reputation: 4071
This is a way to achieve this:
Subscribe the change event of the dropdown and call the action method(with ajax for example) that passes the selected value to the stored procedure.
Upvotes: 0