这可能是我遇到的最令人沮丧的错误。
我有一个与广告位有很多关系的实体频道。在创建时,用户可以选择他们想要属于他们频道的广告位。
我有这个型号:
[Required]
[Display(Name = "Name")]
public string ChannelName { get; set; }
[Display(Name = "Description")]
public string ChannelDescription { get; set; }
//TODO: Add Sub Publisher Drop-Down
[Required(ErrorMessage = "You must select at least one Ad Slot.")]
[Display(Name = "Ad Slot(s)")]
public MultiSelectList AdSlots { get; set; }
这在我看来:
<div class="field">
@Html.LabelFor(m => m.ChannelName)
@Html.TextBoxFor(m => m.ChannelName)
@Html.ValidationMessageFor(m => m.ChannelName)
</div>
<div class="field">
@Html.LabelFor(m => m.ChannelDescription)
@Html.TextAreaFor(m => m.ChannelDescription, new { @class = "description" })
@Html.ValidationMessageFor(m => m.ChannelDescription)
</div>
<div class="field">
@Html.LabelFor(m => m.AdSlots)
@Html.ListBoxFor(m => m.AdSlots, new MultiSelectList(new[] { new { Value = "", Text = "" } }, "Value", "Text", new[] { "" }), new { Class = "multiselect", Multiple = "multiple", Size = 12 })
@Html.ValidationMessageFor(m => m.AdSlots)
</div>
这是我处理处理的控制器操作:
//GET: /publishers/channels/new
public ActionResult New()
{
return View();
}
//POST: /publishers/channels/new
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult New(Models.Channels.Create channelModel)
{
if (ModelState.IsValid)
{
// Channel
Core.Linq.APMaster.Channel channel = new Core.Linq.APMaster.Channel();
channel.PublisherId = PublisherId;
channel.Guid = Guid.NewGuid();
channel.ChannelName = channelModel.ChannelName;
channel.ChannelDescription = channelModel.ChannelDescription;
channel.DateCreated = DateTime.UtcNow;
channel.UserCreated = PublisherId;
//TODO: Fix CreatedFromIP data-type bug.
channel.CreatedFromIP = 0;
channel.IsActive = true;
channel.IsCustom = false;
myDBContext.APMasterDBC.Channels.InsertOnSubmit(channel);
// Ad Slots
foreach (SelectListItem adSlotModel in channelModel.AdSlots)
{
Core.Linq.APMaster.ChannelAdSlot channelAdSlot = new Core.Linq.APMaster.ChannelAdSlot();
channelAdSlot.ChannelId = channel.ChannelId;
channelAdSlot.AdSlotId = int.Parse(adSlotModel.Value);
channelAdSlot.IsActive = true;
myDBContext.APMasterDBC.ChannelAdSlots.InsertOnSubmit(channelAdSlot);
}
myDBContext.APMasterDBC.SubmitChanges();
TempData["flash"] = "Your Channel Has Been Created";
return RedirectToAction("Index");
}
else
{
TempData["flash"] = "Your Channel Has Not Been Created";
}
return View(channelModel);
}
如您所见,我正在尝试从MultiSelectList插入许多广告位。但是我继续得到:没有为这个对象定义无参数构造函数。
有谁知道这是为什么?有人可以告诉我我做错了什么吗?为什么要扔这个?
答案 0 :(得分:1)
我发现感谢这篇文章: Pass SelectList "SelectedValue" to Controller Action Method
模型类型必须简单(例如int [])然后我使用ViewData来填充列表。