保存radiobutton的状态

时间:2015-07-21 06:48:17

标签: javascript c# jquery asp.net-mvc

我有两个radiobuttons - 不,是的。我想保存单选按钮的状态。但目前的情况是,在保存后,无线电按钮的状态为是或否。因此,如果您选择no并保存然后返回页面,则状态仍为yes。在我看来,我有这个:

<div class="form-group">
        @Html.Label(Resources.Entity.Product.OgoneFuturePrice, new { @class = "text-bold control-label col-md-2" })
        <div class="col-lg-6 col-md-8 col-sm-10 ">
            @Html.Label(Resources.Entity.Product.ShowFuturePriceYes) @Html.RadioButtonFor(model => model.Ogone.FutureProductPrice, true, new { @class = "FutureNewProductPrice" })
            @Html.Label(Resources.Entity.Product.ShowFuturePriceNo)  @Html.RadioButtonFor(model => model.Ogone.FutureProductPrice, false, new { @class = "FutureNewProductPrice" })
        </div>
    </div>

    <div class="form-group" id="NewProductPriceView">
        <div class="form-group">
            @Html.LabelFor(model => model.Ogone.NewProductPriceView, new { @class = "text-bold control-label col-md-2" })
            <div class="col-lg-6 col-md-8 col-sm-10 ">
                <input type="text" pattern="\d+([\.,]\d{2})?" value="@Model.Ogone.NewProductPriceView"
                       name="@Html.NameFor(model=>model.Ogone.NewProductPriceView)" class="form-control"
                       id="@Html.NameFor(model => model.Ogone.NewProductPriceView).ToString().Replace('.','_')"
                       placeholder="@Resources.Entity.Product.OgoneProductPricePlaceholder" />
                @Html.ValidationMessageFor(model => model.Ogone.NewProductPriceView)


            </div>

        </div>



        <div class="form-group">
            @Html.LabelFor(model => model.Ogone.NewProductPriceDateView, new { @class = "text-bold control-label col-md-2" })
            <div class="col-lg-6 col-md-8 col-sm-10 ">
                <input type="text" value="@Model.Ogone.NewProductPriceDateView"
                       id="@Html.NameFor(model => model.Ogone.NewProductPriceDateView).ToString().Replace('.','_')"
                       class="form-control datepicker"
                       name="@Html.NameFor(model => model.Ogone.NewProductPriceDateView)"
                       data-val="true"
                       data-pattern="@ViewHelper.GetJSLocaleDateFormat()"
                       data-val-checknewproductpricedate="@Resources.Entity.Product.OgoneNoNewPriceDate"
                       data-val-validatenewproductpricedate="@Resources.Entity.Product.OgoneInvalidNewPriceDate" />
                @Html.ValidationMessageFor(model => model.Ogone.NewProductPriceDateView)
            </div>
        </div>
    </div>


    <script>
        (function ($) {
            $.validator.addMethod("checknewproductpricedate", function (val, el) {
                if ($("#Ogone_NewProductPriceView").val().length != 0)
                    return val.length != 0;

                return true;
            });

            $.validator.addMethod("validatenewproductpricedate", function (val, el) {
                // Checken of de datum in de toekomst ligt...
                var v = getDateFromInput(val, el);

                return (v > new Date());
            });

            $.validator.unobtrusive.adapters.addBool("checknewproductpricedate");
            $.validator.unobtrusive.adapters.addBool("validatenewproductpricedate");
        })(jQuery);

    </script>

</div>

@if (Model.Ogone.FutureProductPrice == false) {

    <script>
        $(document).ready(function () {
            $('#NewProductPriceView').hide();
        });


    </script>

}

这是javascript:

$(".FutureNewProductPrice").change(function () {
        if ($(this).val() == "True") {
            $('#NewProductPriceView').show();
        }
        else {
            $('#NewProductPriceView').hide();
    }
   });

这就是逻辑:

 internal void Deserialize(EditProductModel model)
        {
            XDocument settings = XDocument.Parse(model.Product.PaymentSettings);

            float price;
            XElement settingsElement = settings.Root.Element("productprice");
            if (settingsElement != null &&
                float.TryParse(settingsElement.Value, System.Globalization.NumberStyles.Currency, System.Globalization.CultureInfo.InvariantCulture, out price))
                model.Ogone.productPrice = price;

            settingsElement = settings.Root.Element("newproductprice");
            if (settingsElement != null) {
                XElement newPriceElement = settingsElement.Element("productprice");
                if (newPriceElement != null &&
                    float.TryParse(newPriceElement.Value, System.Globalization.NumberStyles.Currency, System.Globalization.CultureInfo.InvariantCulture, out price))
                    model.Ogone.newProductPrice = price;

                newPriceElement = settingsElement.Element("effectivedate");
                DateTime dt;
                if (newPriceElement != null &&
                    DateTime.TryParseExact(newPriceElement.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                    model.Ogone.newProductPriceDate = dt;

                XElement futureProductPrice = settings.Root.Element("FutureProductPrice");
                if (futureProductPrice != null && !String.IsNullOrWhiteSpace(futureProductPrice.Value))
                    FutureProductPrice = XmlConvert.ToBoolean(futureProductPrice.Value);
                else
                    FutureProductPrice = true;
            }
        }

这是无线电按钮的负责人:

 XElement futureProductPrice = settings.Root.Element("FutureProductPrice");
                if (futureProductPrice != null && !String.IsNullOrWhiteSpace(futureProductPrice.Value))
                    FutureProductPrice = XmlConvert.ToBoolean(futureProductPrice.Value);
                else
                    FutureProductPrice = true;

但无论你选择什么(是或否),它总是:

  FutureProductPrice = true;

这是序列化方法:

internal string Serialize(EditProductModel model)
        {
            XDocument settings = new XDocument(new XElement("settings"));

            settings.Root.Add(new XElement("productprice", model.Ogone.productPrice.ToString("F2", CultureInfo.InvariantCulture)));




            if (newProductPrice.HasValue) {
                if (!newProductPriceDate.HasValue)
                    throw new Exception("No date set for new product price");

                settings.Root.Add(
                     new XElement("newproductprice",
                         new XElement("productprice", model.Ogone.newProductPrice.Value.ToString("F2", CultureInfo.InvariantCulture)),
                         new XElement("effectivedate", model.Ogone.newProductPriceDate.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)),
                          new XElement("FutureProductPrice", FutureProductPrice )
                     )
                 );
            }

            return settings.ToString(SaveOptions.OmitDuplicateNamespaces);
        }

我只是在序列化方法中尝试这个:

string IsCheckPDf = HttpContext.Current.Request.Form["model.Ogone.FutureProductPrice"];
                FutureProductPrice = IsCheckPDf.Equals("True", StringComparison.OrdinalIgnoreCase);

我尝试这样的事情:

  XElement futureProductPrice = settings.Root.Element("FutureProductPrice");
                 futureProductPrice.SetAttributeValue("FutureProductPrice", true);
                 if (futureProductPrice != null && !String.IsNullOrWhiteSpace(futureProductPrice.Value) && FutureProductPrice == false)
                    FutureProductPrice = XmlConvert.ToBoolean(futureProductPrice.Value);
                    //FutureProductPrice = true;
                else
                    FutureProductPrice = true;

但接着我收到了这条消息:

Object reference not set to an instance of an object. 

在这一行:

futureProductPrice.SetAttributeValue("FutureProductPrice", true);

如果我这样做:

 XElement futureProductPrice = settings.Root.Element("FutureProductPrice");
                 futureProductPrice.SetValue("FutureProductPrice");
                 if (futureProductPrice != null && !String.IsNullOrWhiteSpace(futureProductPrice.Value) && FutureProductPrice == false)
                    FutureProductPrice = XmlConvert.ToBoolean(futureProductPrice.Value);
                    //FutureProductPrice = true;
                else
                    FutureProductPrice = true;

我明白了:

Object reference not set to an instance of an object. 

在这一行:

 futureProductPrice.SetValue("FutureProductPrice");

如果我这样做:

  XElement futureProductPrice = settings.Root.Element("FutureProductPrice");
                futureProductPrice.SetValue("true");

                 if (futureProductPrice != null && !String.IsNullOrWhiteSpace(futureProductPrice.Value))
                    FutureProductPrice = XmlConvert.ToBoolean(futureProductPrice.Value);

                else
                    FutureProductPrice = true;

我也收到了这个警告:

Object reference not set to an instance of an object.

这是完整的课程:

public class OgoneSettings
    {
        [Display(Name = "OgoneProductPrice", ResourceType = typeof(Resources.Entity.Product))]
        public string ProductPriceView
        {
            get { return this.productPrice.ToString("F2", CultureInfo.CurrentUICulture); }
            set
            {
                if (string.IsNullOrWhiteSpace(value)) {
                    this.productPrice = 0;
                    return;
                }
                float p;
                string inp = value.Replace(',', '.');
                if (!float.TryParse(inp, NumberStyles.Float, CultureInfo.InvariantCulture, out p))
                    throw new Exception("Invalid price: " + value);

                this.productPrice = p;
            }
        }

        /* Checkout id wordt bepaald door de omgeving: Production of Test.
        [Display(Name = "OgoneCheckoutId", ResourceType = typeof(Resources.Entity.Product))]
        public string CheckoutId { get; set; }
        */
        [Display(Name = "NewProductPrice", ResourceType = typeof(Resources.Entity.Product))]
        public string NewProductPriceView
        {
            get
            {
                return this.newProductPrice.HasValue ? this.newProductPrice.Value.ToString("F2", CultureInfo.CurrentUICulture) : "";
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value)) {
                    this.newProductPrice = null;
                    return;
                }
                float p;
                string inp = value.Replace(',', '.');
                if (!float.TryParse(inp, NumberStyles.Float, CultureInfo.InvariantCulture, out p))
                    throw new Exception("Invalid price: " + value);

                this.newProductPrice = p;
            }
        }

        private float? newProductPrice;
        private float productPrice;
        private DateTime? newProductPriceDate;

        public bool FutureProductPrice { get; set; }

        [Display(Name = "NewProductPriceDate", ResourceType = typeof(Resources.Entity.Product))]
        [NewProductPriceValidation(ErrorMessageResourceType = typeof(Resources.Entity.Product), ErrorMessageResourceName = "OgoneNoNewPriceDate")]
        [DateTimeValidation(SenecaFormsServer.SfsHelpers.ValidationType.FutureDate, null, ErrorMessageResourceType = typeof(Resources.Entity.Product), ErrorMessageResourceName = "OgoneInvalidNewPriceDate")]
        public string NewProductPriceDateView
        {
            get
            {
                return newProductPriceDate == null ? "" :
                    newProductPriceDate.Value.ToString(CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern, CultureInfo.CurrentUICulture);
            }
            set
            {
                if (String.IsNullOrEmpty(value)) {
                    newProductPriceDate = null;
                    return;
                }
                string pattern = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.Replace(' ', '-').Replace('/', '-').Replace('.', '-');
                string clientValue = value.Replace(' ', '-').Replace('/', '-').Replace('.', '-');

                DateTime dt;
                if (!DateTime.TryParseExact(clientValue, pattern, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt))
                    throw new Exception("Invalid date: " + value);

                newProductPriceDate = dt;
            }
        }


        internal string Serialize(EditProductModel model)
        {
            XDocument settings = new XDocument(new XElement("settings"));

            settings.Root.Add(new XElement("productprice", model.Ogone.productPrice.ToString("F2", CultureInfo.InvariantCulture)));  




            if (newProductPrice.HasValue) {
                if (!newProductPriceDate.HasValue)
                    throw new Exception("No date set for new product price");




                settings.Root.Add(
                     new XElement("newproductprice",
                         new XElement("productprice", model.Ogone.newProductPrice.Value.ToString("F2", CultureInfo.InvariantCulture)),
                         new XElement("effectivedate", model.Ogone.newProductPriceDate.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)),
                          new XElement("futureProductPrice", true )
                     )
                 );
            }


            return settings.ToString(SaveOptions.OmitDuplicateNamespaces);
        }


        internal void Deserialize(EditProductModel model)
        {
            XDocument settings = XDocument.Parse(model.Product.PaymentSettings);           

            float price;
            XElement settingsElement = settings.Root.Element("productprice");
            if (settingsElement != null &&
                float.TryParse(settingsElement.Value, System.Globalization.NumberStyles.Currency, System.Globalization.CultureInfo.InvariantCulture, out price))
                model.Ogone.productPrice = price;

            settingsElement = settings.Root.Element("newproductprice");
            if (settingsElement != null) {
                XElement newPriceElement = settingsElement.Element("productprice");
                if (newPriceElement != null &&
                    float.TryParse(newPriceElement.Value, System.Globalization.NumberStyles.Currency, System.Globalization.CultureInfo.InvariantCulture, out price))
                    model.Ogone.newProductPrice = price;

                newPriceElement = settingsElement.Element("effectivedate");
                DateTime dt;
                if (newPriceElement != null &&
                    DateTime.TryParseExact(newPriceElement.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                    model.Ogone.newProductPriceDate = dt;


               XElement futureProductPrice = settings.Root.Element("FutureProductPrice");

                 if (futureProductPrice != null && !String.IsNullOrWhiteSpace(futureProductPrice.Value))
                        //futureProductPrice.SetValue("false");
                    FutureProductPrice = XmlConvert.ToBoolean(futureProductPrice.Value);

                else
                    FutureProductPrice = true;
            }
        }
    }

    public class NewProductPriceValidation : ValidationAttribute
    {
        public NewProductPriceValidation()
        {


        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            OgoneSettings o = validationContext.ObjectInstance as OgoneSettings;

            if (String.IsNullOrEmpty(o.NewProductPriceView))
                return null;

            if (String.IsNullOrWhiteSpace(o.NewProductPriceDateView))
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));

            return null;
        }
    }

2 个答案:

答案 0 :(得分:0)

由于我无法对原始问题发表评论,因此我必须在此处写下这样的答案:由于您未获得FutureProductPrice的空结果,因此不表示:

if (futureProductPrice != null && !String.IsNullOrWhiteSpace(futureProductPrice.Value))

条件永远不会被验证,因此未来产品价格。价值&#39;没设置?

尝试通过将FutureProductPrice替换为true来编辑代码的这一部分,如下所示:

settings.Root.Add(
                 new XElement("newproductprice",
                     new XElement("productprice", model.Ogone.newProductPrice.Value.ToString("F2", CultureInfo.InvariantCulture)),
                     new XElement("effectivedate", model.Ogone.newProductPriceDate.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)),
                      new XElement("FutureProductPrice", true )
                 )
);

答案 1 :(得分:0)

我在元素的错误根源。它必须是这样的:

  XElement futureProductPrice = settingsElement.Element("futureproductprice");