【问题标题】:MVC view is calling controller method not properlyMVC 视图调用控制器方法不正确
【发布时间】:2018-01-14 20:09:45
【问题描述】:

我正在 MVC 中构建商店定位器。这是我的控制器:

namespace IWOOv4.Controllers
{
  public class StoreListingController : Controller
  {
    // GET: StoreListing
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Details(string zip)
    {
        List<Site> result = SiteMgmt.GetByZip(zip);
        View().ViewData["sites"] = result;
        return View();
    }

    public ActionResult Details(string city, string st)
    {
        List<Site> result = SiteMgmt.GetByCity(city, st);
        View().ViewData["sites"] = result;
        return View();
    }
  }
}

这是我的观点:

@{
  ViewBag.Title = "Home Page";
}

<div class="container">
  <div class="row">
    <!--HEADER-->
  </div>
  <div class="row sub-header">
    <span>ONLINE ORDERING</span>
  </div>
  <div class="row container-text">
    Find Your Store
  </div>
  <div class="row">
    <div class="input-group">
      <input type="text" class="form-control" placeholder="Search" name="search">
      <div class="input-group-btn">        
        <button class="btn btn-default" type="button" id="searchbutton">
          <i class="glyphicon glyphicon-search"></i>
        </button>
      </div>
    </div>
  </div>
  <div class="row">
    <!--FOOTER-->
  </div>
</div>

<script type="text/javascript">
  $(document).ready(function () {
    $('#searchbutton').on('click', function (event) {
      document.location = '@Url.Action("Details", "StoreListingController")';
    });
  });
</script>

当我调用 Controller 操作时,它不会显示我的商品详情。它将我的 URL 从http://localhost/IWOOv4/Home/Index 更改为http://localhost/IWOOv4/StoreListingController/Details。我查找了如何将控制器操作调用到您的视图中,并且我拥有它的方式似乎还可以。我做错了什么?非常感谢!

【问题讨论】:

    标签: jquery html asp.net-mvc view controller


    【解决方案1】:

    不要在Url.Action的第二个参数后面加上Controller后缀,MVC会在创建路由的时候帮你做:

    document.location = '@Url.Action("Details", "StoreListing")';
    

    【讨论】:

    • 我取消了 StoreListingController 作为第二个参数,现在当我搜索邮政编码时,它会给出错误代码并将 URL 更改为 localhost/IWOOv4/Home/Details。是不是要更改网址?假设在我搜索 zip 或 city 后,Details 操作会列出我的商店。
    • 您显示的代码中没有任何内容会导致这种行为。
    • 那么它可以在控制器中吗?我只是想刷新我对 MVC 的记忆。我已经一年多没用过了。我很迷茫,我花了几个小时试图解决这个问题。在这一点上,我的任务停止了。 :(
    【解决方案2】:

    一个控制器上最多只能有2个同名的动作方法,为了做到这一点,1个必须是[HttpPost],另一个必须是[HttpGet]

    您可能想在这里查看答案:

    Routing: The current request for action [...] is ambiguous between the following action methods

    The current request for action [...] on controller type '...' is ambiguous between the following action methods

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多