【发布时间】:2014-05-08 00:41:54
【问题描述】:
我正在使用 ASP.NET MVC 4 并构建了这些 ViewModel:
public class NotificationViewModel
{
public string GroupDesc { get; set; }
public bool AM { get; set; }
public bool PM { get; set; }
public int MaxNotif { get; set; }
}
public class SettingsViewModel
{
public List<NotificationViewModel> ListNotification { get; set; }
public SettingsViewModel()
{
ListNotification = new List<NotificationViewModel>();
}
}
我的观点:
@model PortailT2A.Models.SettingsViewModel
@{
ViewBag.Title = "Preferences";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<h2>Preferences</h2>
@using(Html.BeginForm("Preferences", "Administrateur", FormMethod.Post))
{
<table id="settingsTable">
<tr>
<th>Groupe</th>
<th></th>
<th>AM</th>
<th>PM</th>
<th>Limite de notifications</th>
</tr>
@for (int i = 0; i < Model.ListNotification.Count(); i++ )
{
var notif = Model.ListNotification[i];
<tr>
<td>@notif.GroupDesc </td>
<td>Heure de notification</td>
<td>@Html.CheckBoxFor(u => notif.AM) </td>
<td>@Html.CheckBoxFor(u => notif.PM) </td>
<td>@Html.TextBoxFor(u => notif.MaxNotif)</td>
</tr>
<tr/>
}
</table>
<input type ="submit" value="Sauvegarder" />
}
我的 HttpGet 方法填充我的 ViewModel 并返回它。
[HttpGet]
public ActionResult Preferences(long idUser)
{
context = new MainDatabaseEntities();
List<NotificationViewModel> notifications = new List<NotificationViewModel>();
SettingsViewModel settings = new SettingsViewModel();
//Population...
return View(settings);
}
但是,当我想保存更改时,我得到了一个为空的 ViewModel,我不明白为什么。有什么想法吗?
编辑:我的发布方法:
[HttpPost]
public ActionResult Preferences(SettingsViewModel sm)
{
//since here my ViewModel is null
context = new MainDatabaseEntities();
Utilisateur user = (from u in context.Utilisateurs where u.Username == User.Identity.Name select u).FirstOrDefault();
//operations...
}
HTML 生成:
<tr>
<td>Groupe B </td>
<td>Heure de notification</td>
<td><input id="notif_AM" name="notif.AM" type="checkbox" value="true" /><input name="notif.AM" type="hidden" value="false" /> </td>
<td><input checked="checked" id="notif_PM" name="notif.PM" type="checkbox" value="true" /><input name="notif.PM" type="hidden" value="false" /> </td>
<td><input id="notif_MaxNotif" name="notif.MaxNotif" type="text" value="10" /></td>
</tr>
【问题讨论】:
-
请同时附上您的后期操作代码
-
我们能看到一个为通知生成的 HTML 样本(可能是一个项目的价值)吗?有些东西告诉我它没有引用
ListNotificaton[0].AM。 [您在for中使用的快捷方式很可能是罪魁祸首,但如果没有生成的 HTML 则无法确定] -
@JeremyCook,给你。
-
@BradChristie:完成了!
标签: c# asp.net-mvc entity-framework viewmodel