1

I'm sorry for my question, but I'm new in MVC.

This is my situation.

In my view, I have a Model (@model DAEF.Models.M_Generic)

and I want to compare 2 fields. My question is, how can I use the javascript

for do that ?

Below my example code with 2 dates.

    @model DAEF.Models.M_Generic

    <script type="text/javascript">
        function CompareDate() {
            var dSart = "<%=model.Dat_Start%>";
            var dEnd = "<%=model.Dat_End%>";

            if (dEnd > dSart) {
                alert("Date One is greather then Date Two.");
            }
        }
        CompareDate()
    </script>

@using (Html.BeginForm("Ask_History", "Corr_Exit"))
{

    @Html.AntiForgeryToken()

    <div class="row">

        @Html.LabelFor(model => model.Dat_Start, new { @class = "control-label col-sm-2" })
        <div class="col-sm-3">
            @Html.TextBoxFor(model => model.Dat_Start, new { @class = "DateTimePicker form-control" })
            @Html.ValidationMessageFor(model => model.Dat_Start, "", new { @class = "text-danger" })
        </div>

        @Html.LabelFor(model => model.Dat_End, new { @class = "control-label col-sm-2" })
        <div class="col-sm-3">
            @Html.TextBoxFor(model => model.Dat_End, new { @class = "DateTimePicker form-control" })
            @Html.ValidationMessageFor(model => model.Dat_End, "", new { @class = "text-danger" })
        </div>

    </div>    
}

2 Answers 2

1

You can use ToShortDateString() and convert that string to javascript Date like:

 <script type="text/javascript">
                function CompareDate() {
                    var dSart =new Date("@model.Dat_Start.ToShortDateString()");
                    var dEnd = new Date("@model.Dat_End.ToShortDateString()");

                    if (dEnd > dSart) {
                        alert("Date One is greather then Date Two.");
                    }
                }
                CompareDate()
            </script>
Sign up to request clarification or add additional context in comments.

Comments

1

Since you are comparing properties of the model, you do not need javascript variables.

function CompareDate() {
  @if (model.Dat_End > model.Dat_Start) {
    alert("Date One is greather then Date Two.");
  }
}
CompareDate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.