在输入对象中有不同的属性名在动作参数中有不同的属性名

本文关键字:属性 参数 输入 对象 | 更新日期: 2023-09-27 18:17:16

我有一种情况,我正在传递一些值从查询字符串和一些值我从自定义路由段。

例如我的url是

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映射它,但我只想这样做。

Thanks in advance

在输入对象中有不同的属性名在动作参数中有不同的属性名

我们可以通过使用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;
}
}