【问题标题】:MVC JSON ActionResult automatically routing to the Index ActionResultMVC JSON ActionResult 自动路由到 Index ActionResult
【发布时间】:2014-10-25 19:10:54
【问题描述】:

我在控制器中有一个 ActionResult 用于反馈页面,我正在尝试使用级联下拉列表,通过将度假村列表限制为先前选择的国家/地区来简化 UI 的使用。

当使用 ajax(json) 回调控制器时,页面索引的 ActionResult 被调用,因此级联列表不起作用。

[HttpPost]
    public ActionResult GetResorts(string selectedcountry)
    {
        using (HalsburyEntities ctx = new HalsburyEntities())
        {
            List<tblSkiResort> resorts = (from r in ctx.tblSkiResorts
                                          join c in ctx.tblGlobalCountries on r.countryId equals c.CountryID
                                          where c.CountryName == selectedcountry
                                          select r).ToList();
            return Json(resorts, JsonRequestBehavior.DenyGet);
        }

    }
[HttpPost]
    public ActionResult Index(SkiTripEnquiryViewModel stevm)
    {
        // Do Stuff
        return RedirectToAction("thanks");
    }
    public ActionResult Thanks()
    {
        return View();
    }
     public ActionResult Index(string resort, string hotelname)
    {
        //DoStuff

        return View(stevm);
    }

由于 Index 的 ActionResult 被调用,致谢页面总是返回到 AJAX Post 中“成功”的数据中。

JS

   $(function () {
    $('#Country').change(function(){
        $.ajax({
            url: '@Url.Action("GetResorts", "SkiTripEnquiry")',
            type: "POST",
            datatype: "JSON",
            data: { 'selectedcountry': $(this).val() },
            success: function (data) {
                alert("Hello World");
            }
        });
    });
});

CSHTML - 表单开始到下拉字段集结束

@using (Html.BeginForm("SubmitEnquiry", "SkiTripEnquiry", FormMethod.Post))
{

@Html.ValidationSummary(true, "Please correct the errors")
<span style="color:#ff0000;font-weight:bold">@Model.SuccessMessage</span>
<fieldset>
   <legend>Resort:</legend>

   <div class="enquiryDestination ">

      <table style="clear: both;">
          <tr id="" style="height: 50px; padding: 5px;">
              <td style="width: 187px;">
                  Country
              </td>
              <td>
                  @Html.DropDownListFor(x => x.Country, Model.Countries, "All", new { style = "width:212px; padding: 5px;", onfocus = "showHelp('box2', 'Countries');", name = "Countries;" })

              </td>
          </tr>
         <tr id="" style="height: 50px; padding: 5px;">
           <td style="width: 187px;">
             Destination
           </td>
           <td>
           @*@Html.DropDownListFor(x => x.ResortName, Model.ResortNames, "All", new { style = "width:212px; padding: 5px;", onfocus = "showHelp('box2', 'ResortNames');", name = "ResortNames;" })*@
               Resort:
               @Html.DropDownListFor(x => x.SelectedResort, Enumerable.Empty<SelectListItem>())
           </td>
         </tr>
          <tr id="" style="height: 50px; padding: 5px;">
              <td style="width: 187px;">

              </td>
              <td>Add Destination</td>
          </tr>

          </table>
       </div>
       </fieldset>

我不确定我错过了什么。特别是当我按名称引用确切的操作结果时。我也尝试将 GetResorts 方法变成 JsonResult

编辑:它看起来毕竟是路由。当前路由是:

routes.Add(new Route("skitripenquiry/thanks",
                   new RouteValueDictionary(
                   new { controller = "skitripenquiry", action = "Thanks" }),
                   new HyphenatedRouteHandler()));


routes.Add(new Route("skitripenquiry/{resort}/{hotelname}",
                   new RouteValueDictionary(
                   new { controller = "skitripenquiry", action = "Index", resort = "", hotelname = "" }),
                   new HyphenatedRouteHandler()));

因此我添加了:

routes.Add(new Route("skitripenquiry/GetResort",
                   new RouteValueDictionary(
                   new { controller = "skitripenquiry", action = "GetResort", selectedcountry = "" }),
                   new HyphenatedRouteHandler()));`

但这不起作用

【问题讨论】:

  • 您的代码看起来不错,问题一定出在其他地方。
  • 任何关于可能在哪里的线索?
  • 也许您可以尝试使用 ajax 方法:$(this).find(":selected").val();而不仅仅是 $(this).val()。在我的一个项目中,我遇到了这个问题,并且一切正常,也许你可以试一试
  • @JorgeF 恐怕不走运,不过是个好主意!,我也尝试将其更改为 $('#Country').val() 无济于事
  • 所以调用 Index 操作而不是 GetResorts 操作?你有包装控件的表单吗?如果是的话,你能把那个也发一下吗?

标签: jquery ajax asp.net-mvc json asp.net-mvc-3


【解决方案1】:

你已经声明了

public ActionResult GetResorts(string selectedcountry)
    {
    ..
    }

然后返回:

返回 Json(..)

尝试使用“public JsonResult GetResorts”

更新: 我有类似的情况,我更喜欢在第二个下拉框中动态填充子列表)。在您的 JavaScript 代码中尝试这样的操作:

$('#Country').change(function () {
    var C_Code = $('#Country').val();
    C_Code = $.trim(C_Code);
    $.getJSON(BASE_URL + 'Area/blabla/ResortList/', { CC_Code: C_Code }, function (data) { 
        var items = '<option>Select a Resort</option>';
        $.each(data, function (i, cc_code) {
            items += "<option value='" + cc_code.Value + "'>" + cc_code.Text + "</option>";
        });
        $('#ResortID').html(items);
        $('#ResortID').show();
    });
});

【讨论】:

【解决方案2】:

恐怕我只能提供调试技术。希望这会让您朝着正确的方向前进。

  • GetResorts 上设置断点以查看它是否被击中。如果没有,请在路由配置文件中检查您的路由。有时它位于 Global.asax 或解决方案中的单独配置文件中。

  • 检查浏览器开发工具中的网络选项卡。它应该向 /SkiTripEnquiry/GetResorts 发出 POST 请求。如果没有,请确保 change 事件没有在某处被覆盖。

如果所有其他方法都失败了,请使用现场检查输出 HTML。右键单击>查看源代码并确保代码看起来正确。

您应该看到的内容类似于:

url: '/SkiTripEnquiry/GetResorts'

【讨论】:

  • 对不起,回复太长了:我调试了几次,GetResorts 从来没有被调试器命中,而是进入公共ActionResult Index(string resort, string hotelname) 方法,并将resort sring 作为'GetResorts ' 尽管即时窗口中的请求是 localhost:57926/SkiTripEnquiry/…
【解决方案3】:

在路由中,操作名称拼写错误。您提到的操作名称是 GetResorts,但在您的路由中它说 GetResort。可能是因为它找不到 GetResort,它被重新定向到可能指向索引操作的默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多