本文介绍了我是Mvc的新手,我遇到过对象引用空错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@model MVCStrongTypeViewExample.Models.EmployeeViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Search", "Home"))
{
@Html.LabelFor(model => model.filter.EmpNo)
@Html.TextBoxFor(model => model.filter.EmpNo) <br />
@Html.LabelFor(model => model.filter.EmpName)
@Html.TextBoxFor(model => model.filter.EmpName) <br />
<input type="submit" value="Edit Product" />
}
<table>
<thead>
<tr>
<th>EmpNo</th>
<th>Name</th>
<th>Designation</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
@foreach (var employee in Model.EmployeeTablelist)
{
<tr>
<td>@employee.EmpId</td>
<td>@employee.EmpName</td>
<td>@employee.Desgination</td>
<td>@employee.mobile_no</td>
</tr>
}
</tbody>
</table>
控制器代码
controller code
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Search(EmployeeViewModel Model)
{
EmployeeViewModel model = new EmployeeViewModel();
if (ModelState.IsValid && Model !=null)
{
using (TestEntities data=new TestEntities())
{
model.EmployeeTablelist = (from tablist in data.Employes where tablist.EmpName.Contains(Model.filter.EmpName) || tablist.EmpId.Equals(Model.filter.EmpNo) select new EmployeeListItem() { EmpName = tablist.EmpName, Desgination = tablist.Desgination, mobile_no = tablist.mobile_no }).ToList();
}
}
return View(model);
}
Class EmployeeViewModel
Class EmployeeViewModel
public class EmployeeViewModel
{
public EmployeeViewModel() { filter = new EmployeeFilter(); EmployeeTablelist = new List<EmployeeListItem>(); }
public EmployeeFilter filter { get; set; }
public List<EmployeeListItem> EmployeeTablelist { get; set; }
}
推荐答案
这篇关于我是Mvc的新手,我遇到过对象引用空错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!