0

クエリ文字列からいくつかの値を渡し、カスタム ルート セグメントから取得しているいくつかの値を渡す状況があります。

たとえば、私の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)
{

}

アクションで入力を取得したときに、クエリ文字列パラメーターをカスタム プロパティ名にマップできる方法はどれでもあります。

コンテキストからオブジェクトを取得した後、オートマッパーを使用してマップできることはわかっていますが、この方法のみが必要です。

前もって感謝します

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 に答える