0

(これが冗長に思われる場合はお詫びします-関連するすべてのコードを提供しようとしています)

VS2010 にアップグレードしたばかりですが、新しい CustomModelBinder を機能させようとして問題が発生しています。

MVC1 では、次のように記述します。

public class AwardModelBinder: DefaultModelBinder
{
    :
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // do the base binding to bind all simple types
        Award award = base.BindModel(controllerContext, bindingContext) as Award;

        // Get complex values from ValueProvider dictionary
        award.EffectiveFrom = Convert.ToDateTime(bindingContext.ValueProvider["Model.EffectiveFrom"].AttemptedValue.ToString());
        string sEffectiveTo = bindingContext.ValueProvider["Model.EffectiveTo"].AttemptedValue.ToString();
        if (sEffectiveTo.Length > 0)
            award.EffectiveTo = Convert.ToDateTime(bindingContext.ValueProvider["Model.EffectiveTo"].AttemptedValue.ToString());
        // etc

        return award;
    }
}

もちろん、カスタム バインダーを Global.asax.cs に登録します。

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);

        // register custom model binders
        ModelBinders.Binders.Add(typeof(Voucher), new VoucherModelBinder(DaoFactory.UserInstance("EH1303")));
        ModelBinders.Binders.Add(typeof(AwardCriterion), new AwardCriterionModelBinder(DaoFactory.UserInstance("EH1303"), new VOPSDaoFactory()));
        ModelBinders.Binders.Add(typeof(SelectedVoucher), new SelectedVoucherModelBinder(DaoFactory.UserInstance("IT0706B")));
        ModelBinders.Binders.Add(typeof(Award), new AwardModelBinder(DaoFactory.UserInstance("IT0706B")));
    }

現在、 MVC2では、 base.BindModel への呼び出しがすべてが null のオブジェクトを返すことがわかりました。新しい ValueProvider.GetValue() 関数によって表示されるすべてのフォーム フィールドを反復処理する必要はありません。

Google はこのエラーに一致するものを見つけられないので、何か間違ったことをしていると思います。

これが私の実際のコードです:

私のドメイン オブジェクト (カプセル化された子オブジェクトについてあなたが好きなものを推測してください - それらにもカスタム バインダーが必要になることはわかっていますが、3 つの「単純な」フィールド (つまり、基本型) Id、TradingName、および BusinessIncorporated も null に戻ってきます) :

public class Customer
{
    /// <summary>
    /// Initializes a new instance of the Customer class.
    /// </summary>
    public Customer() 
    {
        Applicant = new Person();
        Contact = new Person();
        BusinessContact = new ContactDetails();
        BankAccount = new BankAccount();
    }

    /// <summary>
    /// Gets or sets the unique customer identifier.
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// Gets or sets the applicant details.
    /// </summary>
    public Person Applicant { get; set; }

    /// <summary>
    /// Gets or sets the customer's secondary contact.
    /// </summary>
    public Person Contact { get; set; }

    /// <summary>
    /// Gets or sets the trading name of the business.
    /// </summary>
    [Required(ErrorMessage = "Please enter your Business or Trading Name")]
    [StringLength(50, ErrorMessage = "A maximum of 50 characters is permitted")]
    public string TradingName { get; set; }

    /// <summary>
    /// Gets or sets the date the customer's business began trading.
    /// </summary>
    [Required(ErrorMessage = "You must supply the date your business started trading")]
    [DateRange("01/01/1900", "01/01/2020", ErrorMessage = "This date must be between {0} and {1}")]
    public DateTime BusinessIncorporated { get; set; }

    /// <summary>
    /// Gets or sets the contact details for the customer's business.
    /// </summary>
    public ContactDetails BusinessContact { get; set; }

    /// <summary>
    /// Gets or sets the customer's bank account details.
    /// </summary>
    public BankAccount BankAccount { get; set; }
}

私のコントローラーの方法:

    /// <summary>
    /// Saves a Customer object from the submitted application form.
    /// </summary>
    /// <param name="customer">A populate instance of the Customer class.</param>
    /// <returns>A partial view indicating success or failure.</returns>
    /// <httpmethod>POST</httpmethod>
    /// <url>/Customer/RegisterCustomerAccount</url>
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RegisterCustomerAccount(Customer customer)
    {
        if (ModelState.IsValid)
        {
            // save the Customer

            // return indication of success, or otherwise
            return PartialView();
        }
        else
        {
            ViewData.Model = customer;

            // load necessary reference data into ViewData
            ViewData["PersonTitles"] = new SelectList(ReferenceDataCache.Get("PersonTitle"), "Id", "Name");

            return PartialView("CustomerAccountRegistration", customer);
        }
    }

私のカスタムバインダー:

public class CustomerModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult vpResult = bindingContext
            .ValueProvider.GetValue(bindingContext.ModelName);
        // vpResult is null

        // MVC2 - ValueProvider is now an IValueProvider, not dictionary based anymore
        if (bindingContext.ValueProvider.GetValue("Model.Applicant.Title") != null)
        {
            // works
        }

        Customer customer = base.BindModel(controllerContext, bindingContext) as Customer;
        // customer instanitated with null (etc) throughout

        return customer;
    }
}

私のバインダー登録:

    /// <summary>
    /// Application_Start is called once when the web application is first accessed.
    /// </summary>
    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);

        // register custom model binders
        ModelBinders.Binders.Add(typeof(Customer), new CustomerModelBinder());

        ReferenceDataCache.Populate();
    }

...そして私の見解からのスニペット(これはプレフィックスの問題でしょうか?)

    <div class="inputContainer">
        <label class="above" for="Model_Applicant_Title" accesskey="t"><span class="accesskey">T</span>itle<span class="mandatoryfield">*</span></label>
        <%= Html.DropDownList("Model.Applicant.Title", ViewData["PersonTitles"] as SelectList, "Select ...", 
            new { @class = "validate[required]" })%>
        <% Html.ValidationMessageFor(model => model.Applicant.Title); %>
    </div>
    <div class="inputContainer">
        <label class="above" for="Model_Applicant_Forename" accesskey="f"><span class="accesskey">F</span>orename / First name<span class="mandatoryfield">*</span></label>
        <%= Html.TextBox("Model.Applicant.Forename", Html.Encode(Model.Applicant.Forename),
                            new { @class = "validate[required,custom[onlyLetter],length[2,20]]", 
                                title="Enter your forename",
                                maxlength = 20, size = 20, autocomplete = "off",
                                  onkeypress = "return maskInput(event,re_mask_alpha);"
                            })%>
    </div>
    <div class="inputContainer">
        <label class="above" for="Model_Applicant_MiddleInitials" accesskey="i">Middle <span class="accesskey">I</span>nitial(s)</label>
        <%= Html.TextBox("Model.Applicant.MiddleInitials", Html.Encode(Model.Applicant.MiddleInitials),
                            new { @class = "validate[optional,custom[onlyLetter],length[0,8]]",
                                  title = "Please enter your middle initial(s)",
                                  maxlength = 8,
                                  size = 8,
                                  autocomplete = "off",
                                  onkeypress = "return maskInput(event,re_mask_alpha);"
                            })%>
    </div>
4

2 に答える 2

1

MVC 2 では、モデル バインディングが大幅に変更されました。MVC 1 よりも多くの「落とし穴」があります。たとえば、フォームに空の値があると、バインディングが失敗します。これはどれも十分に文書化されていません。現実的には、この問題を診断する唯一の良い方法は、MVC ソース コードを使用してビルドし、バインディングをトレースすることです。

ソース コードが公開されていることをうれしく思います。私はそれなしで迷っていたでしょう。

于 2010-05-19T13:08:41.980 に答える
1

MVC2 RTM ソースをダウンロードしてビルドした後 (Craig のリンクに感謝)、MVC コードをステップ実行することができ、BindProperty メソッド (DefaultModelBinder.cs の 178 行目) に次のテストがあることを発見しました。

protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) {
    // need to skip properties that aren't part of the request, else we might hit a StackOverflowException
    string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);
    if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey)) {
        return;
    }
    :

... ValueProvider ディクショナリには、本質的にカスタム モデル バインダーの bindingContext の ModelName プロパティであるプレフィックスを持つキーが含まれていること。

私の場合、bindingContext.ModelName は「customer」と推定されていたため (私のドメイン オブジェクト タイプからだと思います)、181 行目のテストは常に失敗したため、フォーム値をバインドせずに BindProperty を終了しました。

これが私の新しいカスタム モデル バインダー コードです。

public class CustomerModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // vitally important that we set what is the prefix of values specified in view 
        // (usually "Model" if you've rendered a strongly-typed view after setting ViewData.Model)
        bindingContext.ModelName = "Model"; 
        Customer customer = base.BindModel(controllerContext, bindingContext) as Customer;

        return customer;
    }
}

これが、同様の問題を抱えている他の人の助けになることを願っています。

クレイグの助けに感謝します。

于 2010-05-20T10:48:47.297 に答える