0

我有一种情况,我从查询字符串中传递了一些值,而我从自定义路由段中获取了一些值。

例如我的网址是

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)
{

}

当我在操作中获得输入时,我可以用自定义属性名称映射查询字符串参数吗?

我知道我们可以在从上下文中获取对象后使用自动映射器映射它,但我只想要这种方式。

提前致谢

4

1 回答 1

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;
}
}
于 2013-06-07T06:44:14.743 回答