سؤال

أحتاج إلى تنفيذ وظيفة للسماح للمستخدمين بإدخال السعر بأي شكل من الأشكال ، أي للسماح بـ 10 دولارات ، 10 دولارات ، 10 دولارات ، ... كمدخلات.

أرغب في حل هذا من خلال تنفيذ موثق نموذج مخصص لفئة السعر.

 class Price { decimal Value; int ID; } 

يحتوي النموذج على صفيف أو أسعار كمفاتيح

keys:
"Prices[0].Value"
"Prices[0].ID"
"Prices[1].Value"
"Prices[1].ID"
...

يحتوي ViewModel على عقار أسعار:

public List<Price> Prices { get; set; }

يعمل موثق النموذج الافتراضي بشكل جيد طالما يدخل المستخدم سلسلة قابلة للعلم العشرية في إدخال القيمة. أود السماح لمدخلات مثل "100 دولار أمريكي".

ModelBinder لنوع السعر حتى الآن:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    Price res = new Price();
    var form = controllerContext.HttpContext.Request.Form;
    string valueInput = ["Prices[0].Value"]; //how to determine which index I am processing?
    res.Value = ParseInput(valueInput) 

    return res;
}

كيف يمكنني تنفيذ موثق نموذج مخصص يتعامل مع المصفوفات بشكل صحيح؟

هل كانت مفيدة؟

المحلول

حصلت عليه: النقطة المهمة هي عدم محاولة ربط مثيل سعر واحد ، بل تنفيذ نموذج نموذج List<Price> يكتب:

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        List<Price> res = new List<Price>();
        var form = controllerContext.HttpContext.Request.Form;
        int i = 0;
        while (!string.IsNullOrEmpty(form["Prices[" + i + "].PricingTypeID"]))
        {
            var p = new Price();
            p.Value = Process(form["Prices[" + i + "].Value"]);
            p.PricingTypeID = int.Parse(form["Prices[" + i + "].PricingTypeID"]);
            res.Add(p);
            i++;
        }

        return res;
    }

//register for List<Price>
ModelBinders.Binders[typeof(List<Price>)] = new PriceModelBinder();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top