目前我在学习 MVC 4 时遇到了一些麻烦,我希望有人能提供帮助。据我所知,搜索中没有出现此问题的重复项,但如果有,请指导我。
我的问题是:在我在 index.aspx 页面上显示的学校列表中,是否可以让用户单击“详细信息”链接,以便返回并显示该特定学校的详细信息?我在下面的代码中包含了所有相关信息,但如果它太多,请原谅(我不确定到底需要什么)。
如您所见,ActionResult Index() 带回了我数据库中所有学校的列表。我想要做的是在他们单击“详细信息”时发回,以便 View 返回有关该学校的特定信息。这可能吗?我认为可以只传递被点击的学校的 Id,但是当我回到 DAC 层时,它接受 Id (int) 作为参数,当我希望它返回一个“学校”类型的对象。这有意义吗?
对于它的值(value),我知道一点 Javascript,但不知道 jQuery、JSON 等(还)。
所以我有5层:
我的 View 对象:
SchoolVO.cs:
public int Id { get; set; }
public string Name { get; set; }
public string Slogan { get; set; }
我的数据库访问类:
SchoolDAC.cs
public static School GetSchool(School school)
{
try
{
using (SqlConnection conn = ConnectionHelper.GetConnection("SchoolDB"))
{
SqlCommand cmd = new SqlCommand("Schools.GetSchool", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SchoolId", school.Id);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
school = readRecord(dr);
// readRecord() is just another method that fills the 3 properties of the school object with data from the database.
}
}
return school;
}
}
catch (Exception ex)
{
throw new Exception("Failed to get school", ex);
}
}
我的“业务”层:
SchoolBus.cs:
public static School GetSchool(School school)
{
school = SchoolDAC.GetSchool(school);
return school;
}
我的 Controller :
SchoolController.cs:
public ActionResult Index()
{
List<School> model = SchoolBus.GetAllSchools();
return View(model);
}
[HttpPost]
public ActionResult Index(School school)
{
School model = SchoolBus.GetSchool(school);
return View(model);
}
我的观点:
index.aspx:
<table>
<tr>
<th>
<%: Html.DisplayNameFor(model => model.Id) %>
</th>
<th>
<%: Html.DisplayNameFor(model => model.Name) %>
</th>
<th>
<%: Html.DisplayNameFor(model => model.Slogan) %>
</th>
<th></th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.DisplayFor(modelItem => item.Id) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Name) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Slogan) %>
</td>
<td> <!--- possible to pass an object through here? --->
<%: Html.ActionLink("Sign Up", "Index", new { id=item.Id }) %> |
<%: Html.ActionLink("Details", "Details", new { id=item.Id }) %> |
<%: Html.ActionLink("Delete", "Delete", new { id=item.Id }) %>
</td>
</tr>
<% } %>
</table>
最佳答案
您不应该将整个学校对象传递给 Controller 。我将向您展示我在项目中所做的类似方法:
[HttpGet]
public ActionResult Edit(int id)
{
DbUser editedDbUser = context.Users.Single(x => x.UserId == id);
User editeduser = Mapper.Map<DbUser, User>(editedDbUser);
return View("AccountInfo", editeduser);
}
在我看来,我知道这是 Razor ,但想法是一样的:
<tr>
<td>@(i + 1)</td>
<td>@usersModel[i].LastName</td>
<td>@usersModel[i].FirstName</td>
<td>@usersModel[i].Email</td>
<td>@Html.ActionLink("Edit", "Edit", new { id = @usersModel[i].UserId })</td>
</tr>
为了回答你的问题,这是我的模型——它只是我在传递给 View 之前填充的列表。
public class Users
{
public List<User> UsersBag { get; set; }
}
如果您的模型中没有 ID,则必须具有另一个属性,您可以通过该属性区分列表中的对象,但我建议保留某种 id。
关于c# - 在 MVC 4 中传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18392713/