[英]Alternative to Response.Redirect with Request.Querystring
I've made a mvc4
project in Visual Studio Express 2012 for web
. 我已经在
Visual Studio Express 2012 for web
制作了一个mvc4
项目。 And there I've made a search function. 在那里,我做了一个搜索功能。 And a view to show the result.
并显示结果。
So normally I would have added this to the _Layout.cshtml
. 因此,通常我会将其添加到
_Layout.cshtml
。
if (Request["btn"] == "Search")
{
searchValue = Request["searchField"];
if (searchValue.Length > 0)
{
Response.Redirect("~/Views/Search/Result.cshtml?searchCriteria=" + searchValue);
}
}
And that doesn't work. 那是行不通的。 What whould be the alternative to
Response.Redirect
in mvc4
, which still allows me to keep the searchCriteria to be read with Request.Querystring
at the Result.cshtml
page. 在
mvc4
,谁可以替代Response.Redirect
,这仍然使我可以在Result.cshtml
页面上保留使用Request.Querystring
读取Result.cshtml
。
You should be definetly doing this in your controller, making it return an ActionResult
and returning a RedirectResult, ie: 您应该在控制器中明确地执行此操作,使其返回
ActionResult
并返回RedirectResult,即:
public ActionResult Search(string searchCriteria) {
return Redirect("~/Views/Search/Result.cshtml?searchCriteria="+searchCriteria);
}
Btw, I'd also say don't use neither of the Request stuff (or even Redirects), but actions with parameters that MVC will bind automagically from POST or GET parameters. 顺便说一句,我也要说不要使用Request东西(甚至Redirects),但是要使用带有MVC参数的操作,这些参数将自动与POST或GET参数绑定。 Eg, "www.something.com/search?searchCriteria=hello" will automatically bind the searchCriteria parameter to the Action handling /search.
例如,“ www.something.com/search?searchCriteria=hello”将自动将searchCriteria参数绑定到Action处理/ search。 Or, "www.something.com/search/hello" will bind to the parameter defined into your Routing config.
或者,“ www.something.com/search/hello”将绑定到“路由”配置中定义的参数。
A simple example would be something like this: 一个简单的例子是这样的:
Index.cshtml: Index.cshtml:
@using (Html.BeginForm("Results", "Search", FormMethod.Get))
{
@Html.TextBox("searchCriteria")
<input type="submit" value='Search' />
}
Then the controller: 然后控制器:
public class SearchController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Results(string searchCriteria)
{
var model = // ... filter using searchCriteria
return View(model);
}
}
model
could be of type ResultsViewModel
, which would encase everything you need to display the results. model
的类型可以是ResultsViewModel
,它将包含显示结果所需的所有内容。 This way, your search is setup in a RESTful way - meaning it behaves consistently each time. 这样,您的搜索将以RESTful方式进行设置-表示每次的行为都一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.