繁体   English   中英

通过jQuery从cshtml调用Controller中的Action并返回一个值

[英]calling an Action in the Controller through JQuery from the cshtml and returning a value back

我有一个cshtml页面,有3个文本框和3个下拉列表。

我的想法是让用户在第一个问题下拉列表中做出决定(是/否),并根据此答案填充第二个文本框,并启用第二个下拉列表(是/否),并为第三个下拉列表启用相同的过程文本框。

我现在有以下内容: -

<script type="text/javascript">
$(document).ready(function () {

    //disable the textboxes 
    $("#T_FirstQuestion").attr('disabled', true);
    $("#T_SecondQuestion").attr('disabled', true);
    $("#T_ThirdQuestion").attr('disabled', true);

    //and the dropdowns intially
    $("#SecondQuestYesNo").attr('disabled', true);
    $("#ThirdQuestYesNo").attr('disabled', true);

    $("#FirstQuestYesNo").change(function () {
        val = $("#FirstQuestYesNo").val();
        PostValue(val);

    });

    function PostValue(val) {
        var url = "/Home/DecisionFirstQuest";
        $("#T_SecondQuestion").attr('enabled', true);
        $.ajax({
            type: "POST",
            url: url,
            data: { value: val }
        }).done(function (msg) {
            alert("Data Saved: " + msg);
        });
    }


});

</script>

@using (Html.BeginForm("Decision", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

{
<table>
    <tr>
        <td> <font face="Arial" size="2"><b>1</b></font>
        </td>
        <td>
           @Html.TextBox("T_FirstQuestion", ViewData["T_FirstQuestion"], new { @class = "NormalTextBox" })
        </td>
        <td>
           @Html.DropDownList("FirstQuestYesNo", ViewData["FirstQuestYesNoData"] as SelectList, new { @class = "normalDropdowns" })
        </td>
    </tr>
    <tr>
        <td> <font face="Arial" size="2"><b>1</b></font>
        </td>
        <td>
           @Html.TextBox("T_SecondQuestion", ViewData["T_SecondQuestion"], new { @class = "NormalTextBox" })
        </td>
        <td>
           @Html.DropDownList("SecondQuestYesNo", ViewData["SecondQuestYesNoData"] as SelectList, new { @class = "normalDropdowns" })
        </td>
    </tr>
    <tr>
        <td> <font face="Arial" size="2"><b>1</b></font>
        </td>
        <td>
           @Html.TextBox("T_ThirdQuestion", ViewData["T_ThirdQuestion"], new { @class = "NormalTextBox" })
        </td>
        <td>
           @Html.DropDownList("ThirdQuestYesNo", ViewData["ThirdQuestYesNoData"] as SelectList, new { @class = "normalDropdowns" })
        </td>
    </tr>
</table>
}

我的控制器如下: -

        public ActionResult DecisionFirstQuest(string value)
    {
        string strMessage = "";

        if (value == "Yes")
        {
            strMessage = "You have chosen YES!";
        }
        else
        {
            strMessage = "You have chosen NO!";
        }

        ViewData["T_SecondQuestion"] = strMessage;

        return RedirectToAction("Decision");
    }

    public ActionResult DecisionSecondQuest(string value)
    {
        string strMessage = "";

        if (value == "Yes")
        {
            strMessage = "You have chosen YES!";
        }
        else
        {
            strMessage = "You have chosen NO!";
        }

        ViewData["T_ThirdQuestion"] = strMessage;

        return RedirectToAction("Decision");
    }

    public ActionResult Decision()
    {

        string FirstQuestYesNo = HttpContext.Request["FirstQuestYesNo"];

        ViewData["T_FirstQuestion"] = "First Question Text";

        var ddlYesNoData = new SelectList(new[]
                                      {
                                          new {ID="",Name="Please Select"},
                                          new {ID="Yes",Name="Yes"},
                                          new{ID="No",Name="No"},
                                      },
                        "ID", "Name", 1);

        if (!String.IsNullOrEmpty(FirstQuestYesNo))
            ViewData["FirstQuestYesNoData"] = FirstQuestYesNo;
        else
            ViewData["FirstQuestYesNoData"] = "Yes";

        ViewData["FirstQuestYesNoData"] = ddlYesNoData;
        ViewData["SecondQuestYesNoData"] = ddlYesNoData;
        ViewData["ThirdQuestYesNoData"] = ddlYesNoData;



        return View();
    }

我正在设法获得第一个下拉列表的值,并重定向到决策操作,但是我没有填写第二个问题文本框。 此外,我得到一个带有一些HTML代码的弹出窗口,我想避免。

所以基本上我的问题是,如何填写第二个文本框,并在用户选择(是/否)后,填写第三个文本框。

另外,我使用正确的方法还是有更好的方法来使用MVC?

谢谢你的帮助和时间!

------------------- UPDATE ------------------------------ --------------我决定去寻找一个更简单的例子

<script type="text/javascript">
$(document).ready(function () {

    $("#YesNo").change(function () {
        val = $("#YesNo").val();
        var url = "../Home/Decision";
        $.post(url, { value: val});

    });



});

</script>

@using (Html.BeginForm("Decision", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id="Decision" }))
{

@Html.DropDownList("YesNo", new List<SelectListItem>
                     {
                        new SelectListItem{ Text="Select", Value = "" }, 
                        new SelectListItem{ Text="Yes", Value = "Yes" },
                        new SelectListItem{ Text="No", Value = "No" }
                     })

string FirstQuestText = ViewBag.FirstQuestData;

 @Html.TextBox("T_FirstQuestion", FirstQuestText, new { @class = "NormalTextBox" })   
}

控制器行动: -

        [HttpPost]
    public ActionResult Decision(string value)
    {
        string strMessage = "";
        if (value == "Yes")
        {
            strMessage = "This is the Second Yes Question";
        }
        else
        {
            strMessage = "This is the Second No Question";
        }

        ViewBag.FirstQuestData = strMessage;
        return View();
    }

现在的问题是我正在正确填充ViewBag.FirstQuestData,但它没有显示在@Html.TextBox中

----------------------------------- JSON UPDATE ------------- -------------------------- cshtml

        $("#YesNoQuest1").change(function () {
        alert('change');
        val = $("#YesNoQuest1").val();
        var url = "../Home/Decisions1";
        $.getJSON(url, function(data) {
             alert(data.message);
        });

调节器

        [HttpPost]
    public JsonResult Decisions1(string value)
    {
        string strMessage = "";
        if (value == "Yes")
        {
            strMessage = "This is the Second Yes Question";
        }
        else
        {
            strMessage = "This is the Second No Question";
        }

        return Json(new { message = strMessage }, JsonRequestBehavior.AllowGet);
    }

尝试返回基于字符串的数据,而不是重定向到Action,如下所示:

[HttpPost]
public ActionResult Decision(string value)
{
    string strMessage = "";
    if (value == "Yes")
    {
        strMessage = "This is the Second Yes Question";
    }
    else
    {
        strMessage = "This is the Second No Question";
    }

    ViewBag.FirstQuestData = strMessage;
    return Content(strMessage); //No need to return complete View
}

您可以在Ajax帖子调用中收到此消息,如下所示:

    $("#YesNo").change(function () {
            val = $("#YesNo").val();
            var url = "../Home/Decision";
            $.post(url, { value: val},function(data){ 
                         alert(data);
                        //Here you can right your logic to manipulate data
           });
    });

希望这可以帮助:

-------更新使用JSON数据-------------------这是控制器返回Json:

[HttpGet]
public ActionResult YourController() 
{ 
  //Do your Logic
  return Json(new { message = "Data" }, JsonRequestBehavior.AllowGet);
}

$.getJSON("../YourController", function(data) {
     alert(data.foo);
     alert(data.baz);
});

如果使用“Json result”将Controller的响应返回给View,请在Ajax设置中将数据类型称为“json”

function PostValue(val) {
        var url = "/Home/DecisionFirstQuest";
        $("#T_SecondQuestion").attr('enabled', true);
        $.ajax({
            type: "POST",
            url: url,
            dataType:'json',
            data: { value: val }
        }).done(function (msg) {
            alert("Data Saved: " + msg);
        });
}

并且您可以在“msg”对象中获取结果。

注意:请勿使用getJSON(),因为它会缓存可能导致您的数据与您的存储库不同步的响应。 但你仍然可以在ajax设置中通过settinb cache = FALSE使用它,如下所示:

$ .ajaxSetup({缓存:假});

这行应该在你的ajax调用之前。

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM