我遇到的情况是我从查询字符串传递一些值,并从自定义路径段获取一些值。
例如我的网址是
http://abc.com/{city}/{location}/{category}?q=wine&l=a&l=b&l=c&c=d&c=e&sc=f
///and my input class is below
public class SearchInput
{
public string city{get;set;}
public string location{get;set;}
public string category{get;set;}
public string Query{get;set;}
public string[] Locations{get;set;}
public string[] Categories{get;set;}
public string[] SubCategories{get;set;}
}
and my action is below
public string index(SearchInput searchInput)
{
}
是我在我的操作中输入时可以使用自定义属性名映射查询字符串参数的任何方式。
我知道我们可以在从上下文获取对象后使用automapper映射它但我只想这样。
提前致谢
答案 0 :(得分:0)
我们可以通过使用ModelBinder属性解决上述问题,我使用的是下面的代码,我在Adam Freeman的MVC 3的一些书中找到了
public class PersonModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext) {
// see if there is an existing model to update and create one if not
Person model = (Person)bindingContext.Model ??
(Person)DependencyResolver.Current.GetService(typeof(Person));
// find out if the value provider has the required prefix
bool hasPrefix = bindingContext.ValueProvider
.ContainsPrefix(bindingContext.ModelName);
string searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : "";
// populate the fields of the model object
model.PersonId = int.Parse(GetValue(bindingContext, searchPrefix, "PersonId"));
model.FirstName = GetValue(bindingContext, searchPrefix, "FirstName");
model.LastName = GetValue(bindingContext, searchPrefix, "LastName");
model.BirthDate = DateTime.Parse(GetValue(bindingContext,
searchPrefix, "BirthDate"));
model.IsApproved = GetCheckedValue(bindingContext, searchPrefix, "IsApproved");
model.Role = (Role)Enum.Parse(typeof(Role), GetValue(bindingContext,
searchPrefix, "Role"));
return model;
}
private string GetValue(ModelBindingContext context, string prefix, string key) {
ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);
return vpr == null ? null : vpr.AttemptedValue;
}
private bool GetCheckedValue(ModelBindingContext context, string prefix, string key) {
bool result = false;
ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);
if (vpr != null) {
result = (bool)vpr.ConvertTo(typeof(bool));
}
return result;
}
}