我有ViewModel
public class Magazine_ViewModel
{
public int MagId { get; set; }
public string MagNo { get; set; }
public IEnumerable<Titles_ViewModel> Titles { get; set; }
}
public class Titles_ViewModel
{
public int TitleId { get; set; }
public string TitleName { get; set; }
public int pos { get; set; }
}
在Controller中我喜欢这个
var viewModel = new Magazine_ViewModel
{
Titles = numberTitles
.Select(c => new Titles_ViewModel
{
TitleId = c.TitleId,
TitleName = c.Title.TitleText,
pos=c.position
}).ToList()
};
viewModel.MagNo = magazine.MagNo.ToString();
viewModel.MagId = magazine.Id;
当我检查viewModel.Titles有n条记录是正确的。 现在在视图部分
<div class="editor-label">
@Html.LabelFor(model => model.MagNo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MagNo)
</div>
<div class="editor-field">
@Html.ListBox("wholeTitles")
<input type="button" name="add" id="add" value="add" onclick="addValue()" /><input type="button" name="remove" id="remove" value="remove" onclick="removeValue()"/>
@Html.ListBoxFor(model => model.Titles, new SelectList(Model.Titles, "TitleId", "TitleName"))
</div>
<p>
<input type="submit" value="Save" />
</p>
我将第一个ListBox(wholeTitles)中的新标题添加到第二个ListBox(标题)。现在按下提交按钮,我想将新标题添加到数据库中。
这就是我在Post Action中所做的事情
[HttpPost]
public ActionResult EditTitle(Magazine_ViewModel magazineViewModel)
{
if (ModelState.IsValid)
{
var magazineTitles = new Magazine
{
Id = magazineViewModel.MagId,
NumberTitles = new List<NumberTitle>()
};
foreach (var numberTitle in magazineViewModel.Titles)
{
NumberTitle newNumberTitle = new NumberTitle();
newNumberTitle.MagazineId = magazineViewModel.MagId;
newNumberTitle.TitleId = numberTitle.TitleId;
newNumberTitle.position = 0;
unitOfWork.NumberTitleRepository.Insert(newNumberTitle);
}
}
return View();
}
但是magazineViewModel.Titles显示为null,我不知道应该检查它为什么它是null值。
答案 0 :(得分:0)
您的值不会回发到服务器。在视图中使用以下内容。这应该将标题发布回同一ViewModel中的服务器
for (var i = 0; i < Model.Titles.Count(); i++)
{
@Html.HiddenFor(m => m.Titles[i].TitleId)
@Html.HiddenFor(m => m.Titles[i].TitleName)
}