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

18,896

Solution 1

Make a foreach razor loop within javascript :

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;
    }
    ]
});

Solution 2

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.

Solution 3

For title, you can do 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.

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.

Solution 4

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

Solution 5

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

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

Share:
18,896
Lamloumi Afif
Author by

Lamloumi Afif

Hi, I am a Software Development Engineer with a genuine interest in .Net framework. I enjoy reading books and practising sport. LinkedIn Viadeo

Updated on June 28, 2022

Comments

  • Lamloumi Afif
    Lamloumi Afif almost 2 years

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

    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 Tache in which I'd like to use it's three fields Tache_description, Begin_date and End_date.

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

           <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 events are just for test, and I need to fill events by the value of the Model. For each element like this: title = Tache_description, start = Begin_date and end = End_date.

    So how can I do this task? Any suggestions?

  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    but the model is a list of Tache(description,begin,end)
  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    I have a problem here (x => new { : it didn't accept the lambda expression
  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    but it indicates an error of syntax in the comma in @:{title: @m.Tache_description, start: @m.Begin_date, end : @m.Begin_date }
  • Alexandr Mihalciuc
    Alexandr Mihalciuc almost 11 years
    Yep you need to check if the item is first or not, if it is not first add a commar before "{"
  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    sorry i don't understand what order ?
  • Alexandr Mihalciuc
    Alexandr Mihalciuc almost 11 years
    Look at the updated answer, it has a sample code for checking it
  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    with no change :( the same result
  • Alexandr Mihalciuc
    Alexandr Mihalciuc almost 11 years
    You are probably missing quotes around strings, @:{title: "@m.Tache_description", ...<other properties here>}
  • Alexandr Mihalciuc
    Alexandr Mihalciuc almost 11 years
    can you post the generated javascript?
  • Lamloumi Afif
    Lamloumi Afif almost 11 years
  • Darin Dimitrov
    Darin Dimitrov almost 11 years
    Try putting it on the same line. I have updated my answer. Also make sure that you have used the correct property names on your Tache model in the lambda expression. And by the way if Visual Studio underlines this with red squiggle as error you can ignore it. Visual Studio Intellisense is not intelligent enough. Run your application and see if it works.
  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    the same this error appears : CS1977: Can not use a lambda expression as an argument to a dynamically distributed free by first cast to delegate type or kind of expression tree operation
  • Darin Dimitrov
    Darin Dimitrov almost 11 years
    This should work unless your code is different than what I have shown in my answer. Is your view strongly typed to @model IList<Tache>. I hope you are not attempting to use some ViewBag stuff.
  • Lamloumi Afif
    Lamloumi Afif almost 11 years
    What is the reason of this error CS1977: Can not use a lambda expression as an argument to a dynamically distributed free by first cast to delegate type or kind of expression tree operation ?
  • Darin Dimitrov
    Darin Dimitrov almost 11 years
    The reason is that your model is not @model IList<Tache> or your expression is different than what I have showed in my answer. This error is a very strong indication that you attempted to use a Select LINQ query on a dynamic variable such as ViewBag instead of using the Model as shown in my answer. What I have showed in my answer works. I have tested it.
  • Lamloumi Afif
    Lamloumi Afif almost 11 years