MVC - 如何在视图中使用Javascript?

问题描述 投票:1回答:2

对不起我的问题,但我是MVC的新手。

这是我的情况。

在我看来,我有一个模型(@model DAEF.Models.M_Generic)

我想比较2个字段。我的问题是,我如何使用javascript

这样做?

在我的示例代码下面有2个日期。

    @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>    
}
javascript asp.net-mvc razor
2个回答
1
投票

由于您要比较模型的属性,因此不需要javascript变量。

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

0
投票

你可以使用ToShortDateString()并将该字符串转换为javascript Date,如:

 <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>
© www.soinside.com 2019 - 2024. All rights reserved.