搜索页面没有';t显示在HttpGet请求MVC c#之后

本文关键字:HttpGet 显示 请求 MVC 之后 搜索 | 更新日期: 2023-09-27 18:26:19

我创建了一个页面,其中包含一个字符串,用于搜索供应商列表。我的目标是将它们输出到HTML页面上的网格列表中。奇怪的是,第一个页面加载了,我可以打断代码,直到返回实际列表页面的视图。然而,它从未实际加载。更令人沮丧的是,如果我不将模型传递到网格页面,它会给我典型的"你不能使用空模型",但它仍然无法加载新页面。我试过几个版本。最新情况如下。

        [HttpPost]
    public ActionResult Search(String searchString)
    {
        this.searchString = searchString;
        List<VendorInvoice> v = VendorSearches.publicSearch(searchString);
        test = v;
        ViewData.Model = v;
        TempData.Add("test",v);
        return RedirectToAction("Search");
    }
    [HttpGet]
    public ActionResult Search()
    {
        List<VendorInvoice> v = (List<VendorInvoice>)TempData["test"]; 
        return View("Search",v);
    }

因此,如果我去掉v,那么我会得到关于没有通过模型的错误。如果它在那里,那么什么都不会发生。新页面无法加载。

搜索页面没有';t显示在HttpGet请求MVC c#之后

在HttpPost搜索操作方法中,将结果数据设置为显示在TempData中,并调用RedirectToAction方法。

RedirectToAction向浏览器返回HTTP 302响应,这使得浏览器对指定的动作发出GET请求。这意味着,这将是一个全新的请求再次出现在您的搜索GET操作中。由于Http是有状态的,所以它不知道您在以前的请求中做了什么。TempData中存储的数据对此请求不可用。

您应该做的是,类似于GET操作方法将结果返回到视图。

[HttpPost]
public ActionResult Search(String searchString)
{
    this.searchString = searchString;
    List<VendorInvoice> v = VendorSearches.publicSearch(searchString);
    return View("Search",v);
}

这应该能解决你的问题。但正如Stephen Muecke所提到的,您可以为初始视图和搜索结果视图保留GET操作方法

public ActionResult Search(String searchString="")
{
    List<VendorInvoice> v = new List<VendorInvoice>();
    v = VendorSearches.publicSearch(searchString);
    return View("Search",v);
}

你的观点

@model List<VendorInvoice>
@using(Html.BeginForm("Search","YourControllerName",FormMethod.GET)
{
  <input type="text" name="searchString" />
  <input type="submit" />
}
<h2>Results</h2>
@foreach(var item in Model)
{
  <p> @item.SomePropertyNameOfYourVendorInvoiceHere </p>
}