ViewBag in jQuery

I use the ViewBag value as follows:

 var date = "@ViewBag.fromDateForEditMode" $('#FromDate').val(date); 

All I get is @ViewBag.fromDateForEditMode and no value.

+4
source share
2 answers

The Razor mechanism is not executed when MVC creates an HTML file, therefore, it will not parse @ViewBag.fromDateForEditMode and replace it with the value of the ViewBag property :)

+3
source

The problem you are facing is that you are trying to enclose @ ViewBag.fromDateForEditMode in quotation marks. When you do this in your jquery function, it causes the browser jquery processor to evaluate it as a literal string when the script is called, rather than letting your razor engine evaluate the contents of the ViewBag while the page is loading.

To work around this problem, use:

var startDate = new Date (@ ViewBag.StartDate.Year.ToString (), @ ViewBag.StartDate.Month.ToString () -1, @ ViewBag.StartDate.Day.ToString ());

This will allow the razor engine to evaluate the contents of the ViewBag before executing the jquery script.

-1
source

Source: https://habr.com/ru/post/1439787/


All Articles