I'm working with ASP.Net MVC with SQL server management studio. Now how would I get a record by a given name and/or id?
Currently, I only find a record using the id which just works fine, but when searching a record by name, it won't find the correct record.
My current code looks something like this:
//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); }
}Now how would I query for an id and a name at the same time?
52 Answers
update your controller
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); }
}update your .cshtml
@using (Html.BeginForm("search", "CrudManually", FormMethod.Post))
{ @Html.TextBox("id") @Html.TextBox("searchString") <br/> <input type="submit" value="Search"/>
} 12 You can get 2 way
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
list.Find(i => i.Property == value); // C# 3.0+if you find any item, you can get that. If you dont find an item, you get null.
Tell me if you resolve :)
2