[英]Why doesn't search operation work in mvc?
几个小时以来我一直被困在这个问题上。当我点击提交按钮时,它没有响应只是刷新页面。
索引控制器
public ActionResult Index()
{
return View(db.Students.ToList());
}
[HttpGet,ActionName("Index")]
public ActionResult SearchIndex(string option, string search)
{
if (option == "Name")
{
var a = db.Students.Where(x => x.StudentName == search || search == null);
return View(a.ToList());
}
else if (option == "Gender")
{
return View(db.Students.Where(x => x.Gender == search).ToList());
}
else
{
return View(db.Students.Where(x => x.RegNo == search || search == null).ToList())
}
}
索引视图
@using(Html.BeginForm("Index","Student",FormMethod.Get)){
<div id="search">
<b>Search By:</b>@Html.RadioButton("option","Name")<b>Name</b>
@Html.RadioButton("option","Gender")<b>Gender</b>
@Html.RadioButton("option","Dept")<b>Dept</b>
@Html.RadioButton("option","RegNo")<b>RegNo</b>
<input type="text" name="text" />
<input type="submit" name="submit" value="Search" class="btn btn-default"/>
</div>
}
可以做些什么来解决问题?
我认为这段代码可以给出更多的结果
public ActionResult SearchIndex(string search)
{
var students = from s in db.Students
select s;
if (!String.IsNullOrEmpty(search))
{
students = students.Where(s => s.StudentName.Contains(search)
|| s.Gender.Contains(search));
}
return View(students.ToList());
}
我不知道您的要求,但是当您将数据搜索到 db 时,您只需要这些数据中的一两个属性。
@using(Html.BeginForm("Index","Student",FormMethod.Get)){
<div id="search">
<input type="text" name="search" />
<input type="submit" name="submit" value="Search" class="btn btn-default"/>
</div>
}
创建一个 POST。
GET 用于请求数据。
您正在尝试发回需要回发的数据(搜索参数)。
[HttpGet] public ActionResult SearchIndex() { return View(); } [HttpPost,ActionName("Index")] public ActionResult SearchIndex(string option, string search) { if (option == "Name") { var a = db.Students.Where(x => x.StudentName == search || search == null); return View(a.ToList()); } else if (option == "Gender") { return View(db.Students.Where(x => x.Gender == search).ToList()); } else { return View(db.Students.Where(x => x.RegNo == search || search == null).ToList()) } }
html 还需要更新以在 using 中使用 FormMethod.Post。
@using (Html.BeginForm("Index", "Student", FormMethod.Post, new { encType = "multipart/form-data" }))
编辑再想一想,我认为您只需要将 multipart/form-data 添加到您的 html 中。
@using (Html.BeginForm("Index", "Student", FormMethod.Get, new { encType = "multipart/form-data" }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.