1

I have an ASP.Net Entity Framework view where I have multiple drop-down lists. Once a user changes an item in this list, I need to call a c# method which is passed the values in all of the dropdown lists to check whether their values overlap.

Currently I have:

@Html.DropDownListFor(model => model.Periods[i].StartTime, new SelectList(Model.DateTimeList, Model.Periods[i].StartTime), new {@class = "form-control", onchange = "dropdownChange()" })

which called a method called dropdownChange():

<script>
    function dropdownChange() {
        @{
            var overlapping = PeriodController.ConfigureViewModel.IsOverLapping(Model);
        }
        console.log("here");
    }
</script>

This method is found by the view but doesn't go into my c# code as I have tested by putting in javascript code and it is run. e.g. the console.log appears but doesnt call the c# code.

Either a solution to this or a more sophisticated way to call a c# method every time a dropdownlist is changed.

Added Ajax Method:

$.ajax({
    type: "POST",
    data: { 'Model': Model },
    success: function(isOverLapping) {
        overLappping = isOverLapping;
        console.log(1);
    },
    error: function() {
        console.log(2);
    }
});
Josh Fletcher
  • 178
  • 1
  • 1
  • 13
  • 2
    you need to call controller action method with Ajax.. – user9405863 Mar 15 '18 at 21:24
  • how about this - https://stackoverflow.com/questions/6119098/how-to-call-controller-actions-using-jquery-in-asp-net-mvc – Nitin Kumar Mishra Mar 15 '18 at 21:34
  • I have added an ajax method but cannot find the Variable _Model_ which could be found when i had it in c#. see original post – Josh Fletcher Mar 15 '18 at 21:38
  • You're mixing up server-side code and client-side code. Your C# Model/class code doesn't exist in the user's browser (in the AJAX area). You can pass an instance of the model, but it will just be the raw data. You can't assign a C# model using JavaScript – ash Mar 15 '18 at 21:44
  • 1
    That makes a lot of sense ash. Thanks – Josh Fletcher Mar 15 '18 at 21:48

1 Answers1

1

One line answer: MVC doesn't work like that.

Longer answer: You can't access the server-side code directly from the browser like that. The most common solution is to use something called AJAX to call the C# function on the server. You then need to write code in the View to handle the response from the server. Have a look at this question and this answer: https://stackoverflow.com/a/16186212/5173105

ash
  • 482
  • 3
  • 9
  • 1
    It's not that MVC doesn't work like that. Browser-based apps in general don't work like that. – John Wu Mar 15 '18 at 21:54