[英]How to get selected index changed value in controller mvc c#
I am getting value in a dropdown list and I wanted to get the selected value in controller when user select any value from the dropdown list. 我在下拉列表中获取值,并且我想在用户从下拉列表中选择任何值时在控制器中获取所选值。 My view is - 我的看法是-
@using (Html.BeginForm("ApReport", "Sales", FormMethod.Post))
{
@Html.DropDownList("Ddl", null, "All", new { @class = "control-label"})
@Html.Hidden("rddl")
}
controller - 控制器-
[HttpPost]
public ActionResult ApReport(ApReport Ddl)
{
string Ddlvalue = string.Empty;
if (Request.Form["rddl"] != null)
{
Ddlvalue = Request.Form["rddl"].ToString();
}
}
but I am not getting any value. 但我没有任何价值。 Also, I donot want to use any submit button. 另外,我不想使用任何提交按钮。
Thanks in advance 提前致谢
The use of Ajax allows you as the developer to update the main view without reloading the entire page, as well as send data to the server in the background. 使用Ajax可以使您作为开发人员在不重新加载整个页面的情况下更新主视图,以及在后台将数据发送到服务器。
This is how I would have accomplished this task. 这就是我完成这项任务的方式。
Firstly, I would have created an action in my controller which returns a JsonResult. 首先,我将在控制器中创建一个动作,该动作返回JsonResult。 This will return a JSON object to your calling jquery code, that you can use to get values back into your views. 这将向您的调用jquery代码返回一个JSON对象,您可以使用该JSON对象将值返回到视图中。 Here is an example of the action method. 这是操作方法的示例。
[HttpGet]
public JsonResult YourActionName(string selectedValue) //Assuming key in your dropdown is string
{
var result = DoYourCalculation(selectedValue);
return Json(new { myResult = result }, JsonRequestBehavior.AllowGet);
}
Now, you need to add your jquery code. 现在,您需要添加您的jquery代码。 I would recommend you place this in a seperate javascript file referenced by your view. 我建议您将其放置在视图引用的单独的javascript文件中。
Here is the JQuery code, with the ajax call to the Action in your controller. 这是JQuery代码,在控制器中带有对Action的ajax调用。 The Ajax call to the server is initiated by the 'change' event of your DropDown, handled in JQuery, as can be seen below. 可以通过在JQuery中处理的DropDown的'change'事件来启动对服务器的Ajax调用,如下所示。
$(function () {
$(document)
.on('change', '#Ddl', function(){
var valueofDropDown = $(this).val();
var url = '/YourControllerName/YourActionName';
var dataToSend = { selectedValue: valueofDropDown }
$.ajax({
url: url,
data: dataToSend,
type: 'GET',
success: function (dataReceived) {
//update control on View
var receivedValue = dataReceived.myResult ;
$('YourControlIDToUpdate').val(receivedValue);
}
})
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.