在开发 ASP.Net MVC 4 应用程序时,我遵循了传递枚举到 html.radiobuttonfor MVC3的答案及其派生的答案,但我的问题仍然存在。
我正在创建一个编辑页面,并希望将状态显示为两个单选按钮“Active”和“InActive”,这些值从数据库中读取为 Enums 1 = Active ,2 = InActive。
问题是,当页面显示时,它显示了对应于数据库值的正确单选按钮,但不允许用户更改/选择其他单选按钮?
任何想法,都让我发疯(同时将属性更改为 chkbox 的 bool 会导致比此时解决的问题更多的问题。)
控制器.....
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle, int id, HttpPostedFileBase Article)
{
try
{
if (ModelState.IsValid)
{
NewsArticle savedArticle= _newsArticle.Get(id);
savedArticle.Body = newsArticle.Body;
savedArticle.Title = newsArticle.Title;
savedArticle.Status = newsArticle.Status;
if(Article == null)
{
newsArticle.ArticleImage = savedArticle.ArticleImage;
}
else
{
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
newsArticle.ArticleImage = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
savedArticle.ArticleImage = newsArticle.ArticleImage;
string imgeName = Path.GetFileName(Article.FileName);
savedArticle.ImageName = imgeName;
}
_uow.SaveChanges();
return RedirectToAction("Index");
}
看法..........
<div class="control-group">
<div class="editor-field">
<label class="control-label">Select Status :</label>
<div class="controls">
@Html.RadioButtonForEnum(n => n.Status)
</div>
</div>
</div>
助手/扩展......
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var names = Enum.GetNames(metaData.ModelType);
var sb = new StringBuilder();
foreach (var name in names)
{
var description = name;
var memInfo = metaData.ModelType.GetMember(name);
if (memInfo != null)
{
var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes != null && attributes.Length > 0)
description = ((DisplayAttribute)attributes[0]).Name;
}
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
sb.AppendFormat(
"<label for=\"{0}\">{1}</label> {2}",
id,
HttpUtility.HtmlEncode(name),
radio
);
}
return MvcHtmlString.Create(sb.ToString());
}
助手正在显示标签,因为它应该从视图中调用。
枚举....
[Flags]
public enum NewsArticleStatus
{
[Display(Name = "Active")]
Active = 1,
[Display(Name = "InActive")]
Inactive = 2
}