[英]how to get selected value of drop down list in asp.net mvc3?
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. 这是我的代码在asp.net MVC3中将数据库中的数据显示到DropDownList中,现在我可以将数据库中的数据显示到dropdownlist中,但是现在我希望,如果我从dropdownlist数据中选择任何东西,我希望该选定值在我的存储过程中传递。 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. 如果有人可以逐步向我解释或提供一些有用的链接。
This code is not completly tested and implemented. 此代码尚未完全测试和实现。
You can acheive it using onchange
event of dropdownlist
. 您可以使用dropdownlist
onchange
事件来实现它。
@Html.DropDownListFor(x => x.SelectedItemValue,new {@onchange="passvalue(this);"})
Handle it using javascript and ajax 使用javascript和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 希望能帮助到你
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. 最简单的方法之一是拥有一个ViewModel,其中包含要在下拉列表中呈现的SelectListItems集合,以及一个要进行选择的项目。 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. 另外,要突出显示该集合,不必一定是SelectListItem
而可以是另一种类型。 Then all you would need to do is change your view to perform a .Select
to convert into a SelectListItem
. 然后,您所需要做的就是更改视图以执行.Select
转换为SelectListItem
。 For simplicity I've just made the ViewModel use it directly. 为简单起见,我只使ViewModel直接使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.