gpt4 book ai didi

asp.net-mvc-3 - 如何将 IEnumerable 对象或数据从 View 传递到 Controller ?

转载 作者:行者123 更新时间:2023-12-05 08:01:47 25 4
gpt4 key购买 nike

我创建了一个强类型 View 。我想将 IEnumerable 对象或数据从 View 传递到 Controller。以下是我的模型 Controller View

我的模型:

public class UserDetailsClass
{
public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
public class Tablefields
{
[Key]
public int ID { get; set; }

[Required(ErrorMessage = "Email is required")]
public string EmailID { get; set; }

[Required(ErrorMessage="Password is required")]
public string Password { get; set; }

[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }

[Required(ErrorMessage = "Last Name is required")]
public string LastName { get; set; }
}
public static List<UserDetails> getalluser()
{
var lst = (from r in context.UserDetails select r);
return lst.ToList();
}
}

我的 Controller

 public ActionResult Test()
{

IList<UserDetailsClass.Tablefields> viewmodel = new List<UserDetailsClass.Tablefields>();
var q = UserDetailsClass.getalluser().ToList();

foreach (SQLOperation.Models.UserDetails item in q)
{
UserDetailsClass.Tablefields viewItem = new UserDetailsClass.Tablefields();

viewItem.EmailID = item.Email;
viewItem.FirstName = item.FirstName;
viewItem.LastName = item.LastName;
viewItem.Password = item.Password;

viewmodel.Add(viewItem);
}
return View(viewmodel);
}

[HttpPost]
public ActionResult Test(IEnumerable<UserDetailsClass.Tablefields> items)
{
return View();
}

我的观点:

@model  IEnumerable<SQLOperation.Models.UserDetailsClass.Tablefields>

@{
ViewBag.Title = "Test";
}

<h2>Test</h2>

@using (Html.BeginForm())
{
<table>
<tr>
<th>
EmailID
</th>
<th>
Password
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th></th>
</tr>

@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmailID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Password)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
</tr>
}
</table>
<input type="submit" value="submit" />
}

我没有在 items 中获得任何值。当我在其上设置断点时,它在 items 中显示 NULL我完全不知道如何将值传递给 Controller

谢谢,阿莫尔

最佳答案

使用 @Html.EditorFor 而不是 @Html.DisplayFor,这样数据绑定(bind)将在您的表单中发生。

此外,由于您使用的是集合,因此您需要迭代字段(简化示例):

                    @for (int row = 0; row < Model.Count; row++)
{
@Html.EditorFor(x => x[row].FirstName )

}

关于asp.net-mvc-3 - 如何将 IEnumerable 对象或数据从 View 传递到 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12073602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com