首先,让我说我是MVC的新手,所以如果看起来很奇怪,那就是原因。我可能没有合适的方法,所以我想要一些指导
我有一个表单,用户可以根据该表单输入页面的翻译。翻译作为TranslationObjects列表处理到页面对象。我需要一种方法来为表单中表示的每个语言分支在表单中呈现输入字段,并让用户填写它们并将它们发送回控制器。 这个例子只是对更复杂模型的简化,但它很好地解释了这个问题。
viewmodel:
public class Page
{
public List<TranslationObject> Translation { get; set; }
}
public class TranslationObject
{
public string LanguageBranch { get; set; }
public string PageName { get; set; }
public string PageDescription { get; set; }
}
用于呈现表单的控制器:
public ActionResult AddPage()
{
var model = new Page {Translation = new List<TranslationObject>()};
foreach (var languageBranch in new[] {"en", "sv", "de"}) // These are normally loaded from database
{
model.Translation.Add(new TranslationObject{ LanguageBranch = languageBranch});
}
return View(model);
}
查看:
@model MvcApplication1.Models.Page
@using (Html.BeginForm("SubmitPage", "Home", FormMethod.Post))
{
foreach (var translation in Model.Translation)
{
@Html.LabelFor(x => x.Translation.FirstOrDefault(y => y.LanguageBranch == translation.LanguageBranch).PageName)
@Html.TextBoxFor(x => x.Translation.FirstOrDefault(y => y.LanguageBranch == translation.LanguageBranch).PageName)<br/>
@Html.LabelFor(x => x.Translation.FirstOrDefault(y => y.LanguageBranch == translation.LanguageBranch).PageDescription)
@Html.TextBoxFor(x => x.Translation.FirstOrDefault(y => y.LanguageBranch == translation.LanguageBranch).PageDescription)
}
<input type="submit" value="Submit"/>
}
该帖子的控制器:
[HttpPost]
public ActionResult SubmitPage(Page model)
{
// Save model to db
return View();
}
Page模型的转换对象始终为null。我知道这可能是错误的方法所以我要求一些方向来呈现对象列表并在发布时将它们返回给控制器
答案 0 :(得分:0)
使用而不是foreach。
@model MvcApplication1.Models.Page
@using (Html.BeginForm("SubmitPage", "Home", FormMethod.Post))
{
for(int i=0;i<Model.Translation.Count;i++)
{
@Html.LabelFor(x => x.Translation[i].PageName)
@Html.TextBoxFor(x => x.Translation[i].PageName)<br/>
@Html.LabelFor(x => x.Translation[i].PageDescription)
@Html.TextBoxFor(x => x.Translation[i].PageDescription)
}
<input type="submit" value="Submit"/>
}
在Page Constructor中初始化翻译