I am trying to create a search page, which searches the details of the user based on the Username. My problem is I am not able to create a strongly typed text box for the search box. I created a Model view and in spite of that I am unable to fix my issue. My View is not able to even compile properly, I am guessing I am going wrong with the Model which binds the view to make it strongly typed. I wish to have 2 text boxes for username and phone number, if the user enters anything inside either of the text box it should return the matching user profile.
This is the View Model:
public class UserSearchViewModel
{
public string userName { get; set; }
public string phoneNum { get; set; }
public IEnumerable<User> user { get; set; }
}
Action method:
public ActionResult Search(UserSearchViewModel mod)
{
IEnumerable<User> u1 = null;
u1 = db.Users.Where(p => p.UserName.Contains(mod.userName) || p.PhoneNum.Contains(mod.phoneNum));
return View(u1);
}
View:
@model HindiMovie.Models.UserSearchViewModel
@using( Html.BeginForm("Search", "User", FormMethod.Get))
{
@Html.TextBox("UserName")
}
<table>
<tr>
<th>@Html.DisplayNameFor(model => model.UserName)</th>
<th>@Html.DisplayNameFor(model => model.FirstName)</th>
<th>@Html.DisplayNameFor(model => model.LastName)</th>
<th>@Html.DisplayNameFor(model => model.PhoneNum)</th>
<th></th>
</tr>
@foreach (var item in Model.user) {
<tr>
<td>@Html.DisplayFor(modelItem => item.FirstName)</td>
<td>@Html.DisplayFor(modelItem => item.LastName)</td>
<td>@Html.DisplayFor(modelItem => item.UserName)</td>
</tr>
}
</table>
A way to go would be to create a wrapper class
public class UserSearchViewModel
{
public string UserName {get;set;}
public string PhoneNumber {get;set;}
public IEnumerable<User> Users {get;set;}
}
The model would be UserSearchViewModel instead of IEnumerable and your foreach would loop through Model.Users instead Model.
This and this are a couple of articles detailing the use of ViewModels (an arbitrary class that exists solely to provide data for a view) vs. using your Enity/Database models directly in the view.
Inside the form element, use
@Html.TextBoxFor(m => m.userName )
@Html.TextBoxFor(m => m.phoneNum)
But the reason you view wont compile is because you model does not contain a properties UserName
, FirstName
etc so you cannot use @Html.DisplayNameFor(m => m.UserName)
in your table headings.
Either hard code them
<th>User name</th>
or use
<th>@Html.DisplayNameFor(m => m.user.FirstOrDefault().UserName)</th>
Note that the collection does not need to contain any items for this to work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.