我在我的项目中使用了 ASP.NET MVC5,并在其中使用了自定义模型绑定。当我在我的模型中获取 IsActive 属性的值时,我遇到了一个问题。IsActive 值必须是“true”或“false”但我得到“true,false” 我怎样才能获得正确的值?
public class BaseModelBinder<TModel> : IModelBinder where TModel : class, new()
{
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
TModel model = (TModel)bindingContext.Model ?? new TModel();
ICollection<string> propertyNames = bindingContext.PropertyMetadata.Keys;
foreach (var propertyName in propertyNames)
{
var value = GetValue(bindingContext, propertyName);
model.SetPropertyValue(propertyName, value);
}
return model;
}
private string GetValue(ModelBindingContext context, string name)
{
name = (context.ModelName == "" ? "" : context.ModelName + ".") + name;
ValueProviderResult result = context.ValueProvider.GetValue(name);
if (result == null || result.AttemptedValue == "")
{
return "<Not Specified>";
}
else
{
return (string)result.AttemptedValue;
}
}
}
我的观点总结:
@using System.ComponentModel
@using Kendo.Mvc.UI
@model Jahan.Blog.ViewModel.ArticleViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Article</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.CheckBoxFor(model => model.IsActive)
@Html.ValidationMessageFor(model => model.IsActive)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.IsActiveNewComment, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.CheckBoxFor(model => model.IsActiveNewComment)
@Html.ValidationMessageFor(model => model.IsActiveNewComment)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>