从布局将数据发送到控制器Asp.Net MVC
我有我的布局视图上我的导航栏的开关按钮,当我点击按钮,它改变了值,并将其发送到控制器:从布局将数据发送到控制器Asp.Net MVC
<input type="button" id="switchbutton" value="Weekend" style="color:blue" onclick="toggle(this)" > <script type="text/javascript">
function toggle(button) {
switch (button.value) {
case "Weekend":
button.value = "Week";
break;
case "Week":
button.value = "Weekend";
break;
}
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{param: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
}
</script>
在控制器我收到该值并将其发送给执行函数的If语句,具体取决于接收到的值。
private string SwitchVal; [HttpPost]
public string AjaxMethod(string param)
{
var d = string.Empty;
switch (param)
{
case "Weekend":
d = "Week";
break;
case "Week":
d = "Weekend";
break;
}
SwitchVal = d;
return d;
}
public JsonResult ModelsUpdate(string SwitchVal)
{
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
的问题是,我按一下按钮,我看不出有什么变化,它似乎只值到达控制器中的第一次。有人可以帮助我吗?
回答:
它不这样工作。您无法在多个不同的请求中保存服务器端的值。也许你可以使用Session
来执行它,但为什么不发布数据ModelsUpdate
而不是AjaxMethod
。在你的情况下,我无法理解AjaxMethod
的目的。
public JsonResult ModelsUpdate(string SwitchVal) {
if (SwitchVal == "Weekend")
{
resultminDate = CalculateminDate(minDate, todayDay);
}
else
{
resultminDate = CalculateminDateWeek(minDate, todayDay);
}
return Json(resultminDate);
}
Ajax
调用看起来像
$.ajax({ type: "POST",
url: "/Home/ModelsUpdate",
data: '{SwitchVal: "' + $(this).val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Return Value: " + response);
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
以上是 从布局将数据发送到控制器Asp.Net MVC 的全部内容, 来源链接: utcz.com/qa/265746.html