如何在cshtml文件中的javascript中使用我的模型的属性

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

我有一个 .NET Framework 4.8 应用程序,我必须使用列表在 javascript 中构建一个日期选择器,该列表是我的 cshtml 文件中的模型。

@{
    ViewBag.Title = "Index";
}

@model WebParetoMVCNEW.Models.Data.Csv.CsvData

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="container mt-5">
    <div class="row">
        <form method="post" enctype="multipart/form-data" 
            action="@Url.Action("UploadFile", "LieferPerformance")">
            <div class="mb-3">
                <label for="csvFile" class="form-label">CSV Datei auswählen</label>
                <input type="file" class="form-control" id="csvFile" name="csvFile">
            </div>
            <button type="submit" class="btn btn-primary">Hochladen und 
                Auslesen</button>
        </form>
    </div>
</div>

<div class="container mt-3">
    <div class="row">
        <div class="col-md-6">
            <input type="text" id="my_date_picker1">
            <button id="datepicker-button">Open Datepicker</button>
        </div>
    </div>
</div>


<script>
    $(document).ready(function () {
        // Serialize the list from the model as JSON within the script block
        var headerListData = @Html.Raw(Json.Serialize(Model.YourListPropertyName));


        // Get the current date
        var currentDate = new Date();

        // Configure the Datepicker using jQuery UI and set the default date to today
        $("#my_date_picker1").datepicker({
            dateFormat: 'yy-mm-dd',
            defaultDate: currentDate,  // Set the default date to today
            beforeShowDay: function (date) {
            var formattedDate = $.datepicker.formatDate('yy-mm-dd', date);
            if (headerList && headerList.indexOf(formattedDate) >= 0) {
                return [true, "av", 'Available'];
            } else {
                return [false, "notav", "Not Available"];
            }
        }
    });

    $("#datepicker-button").on("click", function () {
        $("#my_date_picker1").datepicker("show");
    });
});

这似乎在 javascript 中不起作用:

var headerListData = @Html.Raw(Json.Serialize(Model.Header));

错误消息:当前上下文中不存在名称“Html”

从 Javascript 访问 MVC 的模型属性中所述 它不起作用

有人有想法吗?

javascript c# asp.net-mvc
1个回答
0
投票

您可以在 javascript 中序列化模型对象,然后像 JSON 对象一样使用它来检索所需的属性。

var _model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(@Model));
var headerListData = _model.YourListPropertyName;
© www.soinside.com 2019 - 2024. All rights reserved.