MVC JSON ActionResult自动路由到Index ActionResult

时间:2014-09-01 14:18:07

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

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

当使用ajax(json)回调到控制器时,会调用Index的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);
    }

由于调用了ActionResult for Index,所以Thanks页面总是返回到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()));`

但这不起作用

3 个答案:

答案 0 :(得分:0)

您已宣布

public ActionResult GetResorts(string selectedcountry)
    {
    ..
    }

然后返回:

  

返回Json(..)

尝试使用&#34;公开 JsonResult GetResorts&#34;

更新: 我有类似的情况,我更喜欢在第二个下拉框中动态填充子列表)。在您的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();
    });
});

答案 1 :(得分:0)

我所能提供的只是调试技术,我很害怕。希望这会让你朝着正确的方向前进。

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

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

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

你应该看到的是:

url: '/SkiTripEnquiry/GetResorts'

答案 2 :(得分:0)

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

相关问题