在 asp.net mvc 应用程序中从 Javascript 访问 C# 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17671385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:08:50  来源:igfitidea点击:

Accessing C# variable from Javascript in asp.net mvc application

c#javascript.netasp.net-mvcrazor

提问by Lamloumi Afif

I have a problem in How to use javascript variables in C# and vise versa: I have this Modelpassing to the view:

我有一个问题How to use javascript variables in C# and vise versa:我有这个Model传递给视图:

public List<Tache> Get_List_Tache()
{
    Equipe _equipe = new Equipe();
    List<Tache> liste_initiale = _equipe.Get_List_tache();
    return liste_initiale;
}

It's a list of objects Tachein which I'd like to use it's three fields Tache_description, Begin_dateand End_date.

这是一个Tache我想在其中使用它的三个字段的对象列表Tache_descriptionBegin_dateEnd_date.

In my JavaScript code I have this function and it works fine:

在我的 JavaScript 代码中,我有这个功能,它工作正常:

       <script>

        $(document).ready(function () {
            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            $('#calendar').fullCalendar({
                theme: true,
                header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
                editable: true,
                events: [
                         @foreach (var m in Model.Get_List_Tache())
                          {
                        @:{title : @m.Tache_description , start: @m.Begin_date , end :  @m.Begin_date }
                          }
                        ]

                });
                                        });

</script>

The values of the array eventsare just for test, and I need to fill eventsby the value of the Model. For each element like this: title = Tache_description, start = Begin_dateand end = End_date.

数组的值events只是为了测试,我需要eventsModel. 对于像这样的每个元素:title = Tache_description,start = Begin_dateend = End_date.

So how can I do this task? Any suggestions?

那么我怎样才能完成这个任务呢?有什么建议?

采纳答案by Alexandr Mihalciuc

Make a foreach razor loop within javascript :

在 javascript 中创建一个 foreach razor 循环:

var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
    theme: true,
    header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
    editable: true,
    events: [
    @
    {
      bool isFirst = true;
    }
    @foreach(var m in Model)
    {
        if(!isFirst)
        {
          @:,
        }

        @:{title: @m.Tache_description, ...<other properties here>}

        isFirst = false;
    }
    ]
});

回答by Jeet Bhatt

Try this,

试试这个,

foreach (var item in YourList)
{
    events: [{ title: '@item.title', start: '@item.start', end: '@item.end'}]
}

So, in this code just replace name your model entity.

因此,在此代码中只需替换您的模型实体的名称。

回答by HaoYuan

For title, you can do title = "@Tache_description"

对于标题,您可以执行 title = "@Tache_description"

Not sure about the format/type of your Begin_date and End_date, you may need some function to read the date into a javascript format. Shouldnt be that hard.

不确定您的 Begin_date 和 End_date 的格式/类型,您可能需要一些函数将日期读入 javascript 格式。应该没那么难。

Loop through each element and add the elements to the events array. It is something like...

循环遍历每个元素并将元素添加到事件数组中。它有点像......

events = new Array()
@foreach(tache in list){
    item = { blah : blah, blah : blah };
    events.push(item);
}

for each c# item in this c# list, write these lines of javascript. You may end up with a very long javascript code block, but it should do the trick. Above is pseudocode.

对于此 c# 列表中的每个 c# 项目,编写这些 javascript 行。您最终可能会得到一个很长的 javascript 代码块,但它应该可以解决问题。以上是伪代码。

回答by Marius Schulz

To add to Darin's answer: If you need the server-side variables in an external JavaScript file, take a look this blog post: Generating External JavaScript Files Using Partial Razor Views

要添加到 Darin 的答案:如果您需要外部 JavaScript 文件中的服务器端变量,请查看此博客文章:使用部分 Razor 视图生成外部 JavaScript 文件

回答by FosterZ

1: if your model is expecting the list of Tachethen you have the whole list you can manipulate.

1:如果您的模型需要列表,Tache那么您就拥有了可以操作的整个列表。

2: you can get the data using jquery ajax as json data by calling your action Get_List_Tache().

2:您可以通过调用您的 action 使用 jquery ajax 获取数据作为 json 数据Get_List_Tache()

回答by Darin Dimitrov

Assuming this javascript is inline in your page you could do the following:

假设此 javascript 内联在您的页面中,您可以执行以下操作:

@model IList<Tache>
<script type="text/javascript">
    var events = @Html.Raw(Json.Encode(Model.Select(x => new { title = x.Description, start = x.Begin.ToString("o"), end = x.End.ToString("o") })));

    $('#calendar').fullCalendar({
        theme: true,
        header: { 
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,
        events: events
    });
</script>

This example assumes that your Tache model has properties Description, Beginand End:

此示例假设您的 Tache 模型具有属性DescriptionBegin并且End

public class Tache
{
    public string Description { get; set; }
    public DateTime Begin { get; set; }
    public DateTime End { get; set; }
}

And if this script is in a separate javascript file you could still set a global eventsvariable in your view which will later be used by your script. Alternatively you could fetch this model using an AJAX call.

如果此脚本位于单独的 javascript 文件中,您仍然可以events在视图中设置一个全局变量,稍后您的脚本将使用该变量。或者,您可以使用 AJAX 调用获取此模型。