Home > Blockchain >  Cannot Get alert to show correct Model Value
Cannot Get alert to show correct Model Value

Time:10-24

I have this code

   $(document).ready(function () {
       var edit= @Model.Edit.ToString().ToLower();
       if( edit !=true ) {
           $("#editWriteup").hide();
       }
       var date= @Model.EndDate;
      alert(date);
      $("#date").val(@Model.EndDate).change();
   });
</script>

It pulls from my Model. And my model gets set in the controller correctly and passes it to the page correctly Also on the page load it shows that @Model.Enddate is correct as a date string "03/01/2020" Just on the alert it does not display correctly. I need the date i pass in the alert to be 03/01/2020. Which is what it says the model contains when i inspect it on the page. I originally tried with a DateTime and switched to use a string for the EndDate thinking that may solve it but to no avail.

The value that I get for the alert is -2048. Which I have no idea where it would even get -2048. It also got -2048 when i passed the datetime value and tried to convert it to a string. Also @Model.Edit works correctly as intended

   ...lastDate = lastSummaryWriteup.EndDate.ToString("MM/dd/yyyy");
                edit = true;
            }

            var model = new SModel
            {               
                EndDate = lastDate,
                Edit = edit
            };

public class SModel
    {  
        public string EndDate { get; set; }

        public bool Edit { get; set; }
    }

Can anyone point me in the right direction to get the alert to actually have the correct string value.

CodePudding user response:

Your issue is that your Razor has rendered your date as a 3 numbers, not as as string.

Always look at the rendered HTML/js.

Your code:

var date = @Model.EndDate;

will be being rendered as (for example):

var date = 01-27-2022;

which js sees as 1 - 27 - 2022 which = -2048

The first step would be to put quotes around your value, as your model has string EndDate { get;set; }, I would start with:

var date = "@Model.EndDate";

You may need to reformat it, eg to yyyy-mm-dd but certainly test for days >12th

  • Related