将数据从布局发送到控制器Asp.Net MVC

问题描述 投票:0回答:1

我在布局视图上的导航栏上有一个开关按钮,当我单击按钮时它会更改值并将其发送到控制器:

<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);
    }

问题是我点击按钮,我没有看到任何变化,似乎值只是第一次到达控制器。有人可以帮我这个吗?

c# asp.net asp.net-mvc controller
1个回答
1
投票

它不像那样工作。您无法在服务器端保留多个不同请求的值。也许你可以使用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);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.