[英]How do I redirect to the next page after pressing the submit button?
我正在使用ASP.NET MVC 4和C#创建一个站点。 主页是一个搜索栏,带有带有“搜索”标签的提交按钮。 我希望用户能够输入音乐艺术家并按下“搜索”按钮。 然后,该网站应转到包含结果的“结果”页面。
按下搜索按钮后,我无法进入结果页面。
我的视图Index.cshtml表单如下所示:
<form method="post" class="form-inline">
<div class="row">
<div class="col-md-1" style="min-width:300px">
<input type="text" name="Artist" class="form-control box-shadow--4dp" placeholder="Artist Name" />
</div>
<div class="col-md-2">
<input type="submit" class="btn btn-default box-shadow--4dp" value="Search" />
</div>
</div>
</form>
我的HomeController.cs看起来像这样:
namespace Task2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
// edit
[HttpPost]
public ActionResult Index(string Artist)
{
return RedirectToAction("Result", "Home");
}
public ActionResult Contact()
{
ViewBag.Message = "For more information you can contact me using the form below.";
return View();
}
public ActionResult Result(string Artist)
{
ViewBag.Message = Artist;
return View();
}
}
}
因此,总而言之,如何使“提交”按钮将用户重定向到包含结果的“结果”页面?
当前设置HTML的方式是,表单将POST到控制器的Index
方法。
要进行重定向,您可以执行以下操作:
[HttpPost]
public ActionResult Index(string searchTerm)
{
//handle your search stuff here...
return RedirectToAction("Results", "Home");
}
但是,您可以将当前表单包装在HTML.BeginForm
然后发布到除Index方法之外的特定Action方法中-也许发布到搜索Action方法中,然后该方法将重定向到Results,例如传递结果集合。
如果要将输入作为查询字符串,则只需将form方法更改为GET
。 它将带您将输入重定向为结果字符串作为查询字符串。
@using (Html.BeginForm("Result","Home",FormMethod.Get,new {@class= "form-inline" }))
{
<div class="row">
<div class="col-md-1" style="min-width:300px">
<input type="text" name="Artist" class="form-control box-shadow--4dp" placeholder="Artist Name" />
</div>
<div class="col-md-2">
<input type="submit" class="btn btn-default box-shadow--4dp" value="Search" />
</div>
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.