很长一段时间以来,我一直在尝试使用 cshtml 显示表单,但它给了我很多问题。我正在使用 ASP.NET MVC。
这是我的控制器代码:
[HttpGet]
public ActionResult Search()
{
return View();
}
[HttpPost]
public ActionResult Search(Models.SearchModel user)
{
List<Models.SearchModel> UserList = new List<Models.SearchModel>();
MySqlConnection connection = DBConnect.getconnection(); // setting connection to database
MySqlCommand cmd = new MySqlCommand("GetUsers", connection); // search for procedure called "GetData"
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new MySqlParameter("?search", MySqlDbType.VarChar)); // search parameters, if not looking for anythinf gets all the data
cmd.Parameters["?search"].Value = "%" + "" + "%";
cmd.Parameters["?search"].Direction = ParameterDirection.Input;
MySqlDataReader dr = cmd.ExecuteReader(); // telling program to read Data
while (dr.Read())
{
int id = Convert.ToInt16(dr["ID"]);
string user_name = Convert.ToString(dr["user_name"]); // converting data to a string
Models.SearchModel UserMod = new Models.SearchModel(id, user_name);
UserList.Add(UserMod);
}
dr.Close(); // close
DBConnect.CloseConnection(connection); // closes connection
return View("Search");
}
我的模型:
namespace AOSExpress.Models
{
public class SearchModel
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string user_name;
public string User_Name
{
get { return user_name; }
set { user_name = value; }
}
public SearchModel(int i, string usnm)
{
id = i;
user_name = usnm;
}
}
}
和我的 Search.cshtml:
@model IEnumerable<AOSExpress.Models.SearchModel>
@{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@foreach (var item in Model)
{
@Html.Partial("_SearchModel", item)
}
和 _Search.cshtml
@model AOSExpress.Models.SearchModel
<table style="font-family: Arial; border:1px solid black; width: 300px">
<tr>
<td><b>ID:</b></td>
<td>@Model.Id</td>
</tr>
<tr>
<td><b>Username:</b></td>
<td>@Model.User_Name</td>
</tr>
</table>
错误是:
App_Web_5m4f2la2.dll 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理
附加信息:对象引用未设置为对象的实例。