下午好
我希望这会很好,我自己一个简单的f**k,但我已经深入了,目前不会游泳。
好的,以前我问过这个问题,因此我已经实现了以下内容:
模型
public class CorporateDetails
{
public Guid? Id { get; set; }
[Key]
public int CorporateDetailId { get; set; }
public int? EmsId { get; set; }
public string EmsName { get; set; }
public virtual EmsType EmsType { get; set; }
}
public class EmsType
{
[Key]
public int? EmsId { get; set; }
public string EmsName { get; set; }
public virtual ICollection<EmsType> EmsTypes { get; set; }
}
控制器
public ActionResult Create()
{
ViewBag.EmsId = new MultiSelectList(db.EmsTypes, "EmsId", "EmsName");
return View();
}
看法
<fieldset>
<legend>CorporateDetails</legend>
<div class="editor-label">
@Html.LabelFor(model => model.EmsId, "EmsType")
</div>
<div class="editor-field">
@Html.DropDownList("EmsId", String.Empty)
@Html.ValidationMessageFor(model => model.EmsId)
</div>
<div class="editor-label">
@Html.CheckBoxListFor(model => model.EmsId, (MultiSelectList) ViewBag.EmsId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
此 CheckBoxListFor 使用以下扩展名:
public static class HtmlHelper
{
//Extension
public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty[]>> expression, MultiSelectList multiSelectList, object htmlAttributes = null)
{
//Derive property name for checkbox name
MemberExpression body = expression.Body as MemberExpression;
string propertyName = body.Member.Name;
//Get currently select values from the ViewData model
TProperty[] list = expression.Compile().Invoke(htmlHelper.ViewData.Model);
//Convert selected value list to a List<string> for easy manipulation
List<string> selectedValues = new List<string>();
if (list != null)
{
selectedValues = new List<TProperty>(list).ConvertAll<string>(delegate(TProperty i) { return i.ToString(); });
}
//Create div
TagBuilder divTag = new TagBuilder("div");
divTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
//Add checkboxes
foreach (SelectListItem item in multiSelectList)
{
divTag.InnerHtml += String.Format("<div><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" " +
"value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></div>",
propertyName,
item.Value,
selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
item.Text);
}
return MvcHtmlString.Create(divTag.ToString());
}
}
那么有什么问题呢?
好吧,当我运行它时,我收到一个令人讨厌的错误,告诉我:
“CS0411:无法从用法中推断方法 'Extensions.HtmlHelper.CheckBoxListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Web.Mvc.MultiSelectList, object)' 的类型参数。尝试明确指定类型参数。”
有人可以指出我哪里出错了,因为我在转圈,不确定我错过了什么。
任何帮助将不胜感激。