我有一个包含问题列表的FeedbackViewModel:
public class FeedbackViewModel
{
public List<QuestionViewModel> Questions { get; set; }
}
此QuestionViewModel是一个可以由5种不同类型的问题继承的对象
public class QuestionViewModel
{
public string QuestionText { get; set; }
public string QuestionType { get; set; }
}
其中一个继承问题类型的示例:
public class SingleQuestionViewModel : QuestionViewModel
{
public string AnswerText { get; set; }
}
在控制器中的HttpGet
操作的Index
中,我从数据库中获取问题,并在FeedbackViewModel
中的问题列表中添加正确的问题类型然后我渲染此模型在视图中:
@using (Html.BeginForm())
{
//foreach (var item in Model.Questions)
for (int i = 0; i < Model.Questions.Count; i++)
{
<div class="form-group">
@Html.DisplayFor(modelItem => Model.Questions[i].QuestionText, new { @class = "control-label col-md-4" })
<div class="col-md-6">
@if (Model.Questions[i].QuestionType == "Single")
{
@Html.EditorFor(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
else if (Model.Questions[i].QuestionType == "Multiple")
{
@Html.TextAreaFor(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
else if (Model.Questions[i].QuestionType == "SingleSelection")
{
@Html.RadioButtonForSelectList(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleSelectionQuestionViewModel).SelectedAnswer,
(Model.Questions[i] as OpenDataPortal.ViewModels.SingleSelectionQuestionViewModel).SelectionAnswers)
}
else if (Model.Questions[i].QuestionType == "MultipleSelection")
{
@Html.CustomCheckBoxList((Model.Questions[i] as OpenDataPortal.ViewModels.MultipleSelectionQuestionViewModel).AvailableAnswers)
}
else if (Model.Questions[i].QuestionType == "UrlReferrer")
{
@Html.EditorFor(modelItem => (Model.Questions[i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
</div>
</div>
<br />
}
<br />
<button type="submit">Submit</button>
}
现在,我根本无法在模型中发布问题列表。是否可以发布不同对象类型的列表?
编辑:以下是我使用Fiddler发现的帖子中的数据列表:
答案 0 :(得分:30)
经过大量研究后,我发现了两个解决方案:
一种是编写具有硬编码的Id和名称的HTML 第二个是将ICollection / IEnumerable转换为数组或列表(即IList带有&#39;索引&#39;),并在Controller POST Action中的BindingModel中有一个Array对象。
感谢Phil Haack(@haacked)2008年博文http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/ 这仍然与默认的ModelBinder今天如何为MVC工作有关。 (注意:Phil的文章中关于样本和扩展方法的链接被破坏了)
启发我的HTML片段:
<form method="post" action="/Home/Create">
<input type="hidden" name="products.Index" value="cold" />
<input type="text" name="products[cold].Name" value="Beer" />
<input type="text" name="products[cold].Price" value="7.32" />
<input type="hidden" name="products.Index" value="123" />
<input type="text" name="products[123].Name" value="Chips" />
<input type="text" name="products[123].Price" value="2.23" />
<input type="submit" />
</form>
Post数组看起来有点像:
products.Index=cold&products[cold].Name=Beer&products[cold].Price=7.32&products.Index=123&products[123].Name=Chips&products[123].Price=2.23
型号:
public class CreditorViewModel
{
public CreditorViewModel()
{
this.Claims = new HashSet<CreditorClaimViewModel>();
}
[Key]
public int CreditorId { get; set; }
public string Comments { get; set; }
public ICollection<CreditorClaimViewModel> Claims { get; set; }
public CreditorClaimViewModel[] ClaimsArray {
get { return Claims.ToArray(); }
}
}
public class CreditorClaimViewModel
{
[Key]
public int CreditorClaimId { get; set; }
public string CreditorClaimType { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:N2}")]
public Decimal ClaimedTotalAmount { get; set; }
}
控制器GET:
public async Task<ActionResult> Edit(int id)
{
var testmodel = new CreditorViewModel
{
CreditorId = 1,
Comments = "test",
Claims = new HashSet<CreditorClaimViewModel>{
new CreditorClaimViewModel{ CreditorClaimId=1, CreditorClaimType="1", ClaimedTotalAmount=0.00M},
new CreditorClaimViewModel{ CreditorClaimId=2, CreditorClaimType="2", ClaimedTotalAmount=0.00M},
}
};
return View(model);
}
Edit.cshtml:
@Html.DisplayNameFor(m => m.Comments)
@Html.EditorFor(m => m.Comments)
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(m => Model.Claims.FirstOrDefault().CreditorClaimType)
</th>
<th>
@Html.DisplayNameFor(m => Model.Claims.FirstOrDefault().ClaimedTotalAmount)
</th>
</tr>
<!--Option One-->
@foreach (var item in Model.Claims)
{
var fieldPrefix = string.Format("{0}[{1}].", "Claims", item.CreditorClaimId);
<tr>
<td>
@Html.DisplayFor(m => item.CreditorClaimType)
</td>
<td>
@Html.TextBox(fieldPrefix + "ClaimedTotalAmount", item.ClaimedTotalAmount.ToString("F"),
new
{
@class = "text-box single-line",
data_val = "true",
data_val_number = "The field ClaimedTotalAmount must be a number.",
data_val_required = "The ClaimedTotalAmount field is required."
})
@Html.Hidden(name: "Claims.index", value: item.CreditorClaimId, htmlAttributes: null)
@Html.Hidden(name: fieldPrefix + "CreditorClaimId", value: item.CreditorClaimId, htmlAttributes: null)
</td>
</tr>
}
</table>
<!--Option Two-->
@for (var itemCnt = 0; itemCnt < Model.ClaimsArray.Count(); itemCnt++)
{
<tr>
<td></td>
<td>
@Html.TextBoxFor(m => Model.ClaimsArray[itemCnt].ClaimedTotalAmount)
@Html.HiddenFor(m => Model.ClaimsArray[itemCnt].CreditorClaimId)
</td></tr>
}
表单在Controller中处理:
发布模型:
public class CreditorPostViewModel
{
public int CreditorId { get; set; }
public string Comments { get; set; }
public ICollection<CreditorClaimPostViewModel> Claims { get; set; }
public CreditorClaimPostViewModel[] ClaimsArray { get; set; }
}
public class CreditorClaimPostViewModel
{
public int CreditorClaimId { get; set; }
public Decimal ClaimedTotalAmount { get; set; }
}
控制器:
[HttpPost]
public ActionResult Edit(int id, CreditorPostViewModel creditorVm)
{
//...
答案 1 :(得分:4)
感谢您通过这篇文章指出我正确的方向。我正在努力获得绑定非顺序IDictionary<string, bool>
对象的语法。不确定这是100%正确,但这个Razor代码对我有用:
<input type="hidden" name="MyDictionary.Index" value="ABC" />
<input type="hidden" name="MyDictionary[ABC].Key" value="ABC" />
@Html.CheckBox(name: "MyDictionary[ABC].Value", isChecked: Model.MyDictionary["ABC"], htmlAttributes: null)
如果您需要一个复选框,请务必使用Html.CheckBox而不是标准HTML复选框。如果未提供值,模型将会爆炸,并且Html.CheckBox会生成一个隐藏字段,以确保在未选中复选框时存在值。
答案 2 :(得分:3)
确保按顺序呈现视图,以便Model.Questions[i]
按顺序呈现。
例如,Model.Questions[0], Model.Questions[1], Model.Questions[2]
。
我注意到如果订单不正确,mvc model binder只会绑定第一个元素。
答案 3 :(得分:0)
使用Razor,您可以使用字典实现for循环,而无需更改对象:
@foreach (var x in Model.Questions.Select((value,i)=>new { i, value }))
{
if (Model.Questions[x.i].QuestionType == "Single")
{
@Html.EditorFor(modelItem => (modelItem.Questions[x.i] as OpenDataPortal.ViewModels.SingleQuestionViewModel).AnswerText)
}
...
}
集合需要是List或Array才能使用。
答案 4 :(得分:0)
我使用此代码也许可以帮助
<input type="hidden" name="OffersCampaignDale[@(item.ID)].ID" value="@(item.ID)" />
@Html.Raw(Html.EditorFor(modelItem => item.NameDale, new { htmlAttributes = new { @class = "form-control" } })
.ToString().Replace("item.NameDale", "OffersCampaignDale[" + item.ID+ "].NameDale").Replace("item_NameDale", "NameDale-" + item.ID))
@Html.ValidationMessageFor(modelItem => item.NameDale, "", new { @class = "text-danger" })