我一直在嘗試使用cshtml顯示錶單很長一段時間,它給了我很多問題。我正在使用ASP.NET MVC。如何在cshtml中顯示錶單?
這是我的控制器代碼:
[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>
錯誤是:
類型「System.NullReferenceException」的一個例外發生在App_Web_5m4f2la2.dll但在用戶代碼中沒有處理
其他信息:對象沒有設置爲一個對象的一個實例。
嘗試不使用部分 – Gandarez
您正在向您的視圖傳遞字符串「搜索」,而期望搜索模型集合 – Rex
與問題沒有真正關聯,但是您確定要爲每個結果單獨使用表嗎?或者他們應該是一個更大的表的行? –