【问题标题】:save state of radiobutton保存单选按钮的状态
【发布时间】:2015-07-21 06:48:16
【问题描述】:

我有两个单选按钮 - 否和是。我想保存单选按钮的状态。但目前的情况是单选按钮的状态是保存后是或否。因此,如果您选择否并保存,然后返回页面,则状态仍为是。我认为这是:

<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;
        }
    }

【问题讨论】:

  • 您可以使用缓存来保存状态或尝试将状态存储在日志文件中。
  • @Jaffer。我真的不明白你在说什么。对不起
  • 你能澄清一下你所面临的确切问题吗?
  • 其他属性保存正确。但只有单选按钮的状态不保存。这正是问题所在。
  • FutureProductPrice 为空

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


【解决方案1】:

由于我无法对原始问题发表评论,因此我必须在此处写下此答案作为答案:既然您得到 FutureProductPrice 的空结果,这是否意味着:

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

条件从未验证,因此未设置“futureProductPrice.Value”?

尝试通过将 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 )
                 )
);

【讨论】:

  • 感谢您的回答。那是对的。但是如何设置值?我编辑帖子
  • 您是否尝试过使用 XElement.SetAttributeValue method
  • 不,但是在哪里使用呢?谢谢
  • 在创建xElement futureProductPrice 之后,您应该设置元素的值。对不起,我认为 SetAttributeValue 不是您需要的。您要使用 xElement.setValue 来将元素的值设置为 true 或 false。
  • 使用futureProductPrice.SetValue 而不是futureProductPrice.SetAttributeValue。由于我不是 c# 方面的专家,因此我很抱歉我的回答含糊不清。只是想帮你找出问题所在。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多