我正在使用带有SQL Server Management Studio的ASP.Net MVC。 现在,如何获得具有给定名称和/或ID的记录?
当前,我仅使用ID来查找记录,该记录工作得很好,但是按名称搜索记录时,找不到正确的记录。
我当前的代码如下:
//Student.cs
public partial class Student
{
public int No { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public Nullable<decimal> mobileno { get; set; }
public string Image { get; set; }
}
//Index.cshtml
@using (Html.BeginForm("search", "CrudManually", FormMethod.Post))
{
@Html.TextBox("id")<br/>
@Html.TextBox("searchString")<br/>
<input type="submit" value="Search"/>
}
//CrudManuallyController.cs
public class CrudManuallyController : Controller
{
public ActionResult Index()
{
return View(db.manages.ToList());
//return View();
}
[HttpPost]
public ActionResult search(int id,string searchString,Student students)
{
var query = db.students.Where(d => d.No == id).AsQueryable();
if (!string.IsNullOrEmpty(searchString))
{
query = query.Where(d => d.Name.Contains(searchs)); // generate an error local variable 'searchs' before it is declared.
}
var searchs = query.ToList();
return View("index",searchs);
}
}
现在如何查询ID和名称?
答案 0 :(得分:0)
您可以获得2种方式
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
list.Find(i => i.Property == value); // C# 3.0+
如果找到任何物品,就可以得到。如果找不到项目,则为空。
告诉我,如果您解决:)
答案 1 :(得分:0)
更新您的控制器
public class CrudManuallyController : Controller
{
public ActionResult Index()
{
return View(db.manages.ToList());
//return View();
}
[HttpPost]
public ActionResult search(int? id, string searchString,Student students)
{
//Lambda Linq to entity does not support Int32
//var search = (from d in db.students where d.No == Convert.ToInt32(id) && d.Name == id select d).ToList();
//var search = db.students.Where(d => d.No == Convert.ToInt32(id) && d.Name == id).ToList();
query = db.students.AsQueryable();
if (id.HasValue)
{
var studentId = id.Value;
query = query.Where(d => d.No == studentId);
}
if (!string.IsNullOrEmpty(searchString))
query = query.Where(d => d.Name.Contains(searchString));
var search = query.ToList();
return View("index",search);
}
}
更新您的.cshtml
@using (Html.BeginForm("search", "CrudManually", FormMethod.Post))
{
@Html.TextBox("id")
@Html.TextBox("searchString")
<br/>
<input type="submit" value="Search"/>
}