1

I am trying to pass the @Model.Id from my razor view to the javascript so that I can pass it to the dataTables ajax url but I cant manage to get the value to the javascript file. Even just a point in the right direction would help at this point

Here is the View:

    @model GTravel.Domain.Package    
    @{
        var title = Model.Name;    
    }


   //boring html code


    @section Scripts{
        <script src="~/js/packageCity.js" data-packageId="@Model.Id"></script>
    }

And a snippet of the js:


var dataTable;
var url;
$(document).ready(function () {
    url = "/admin/packageCity/GetAll/" + packageId.toString();
    loadDataTable();
});



function loadDataTable() {

    dataTable = $('#tblData').DataTable({
        "ajax": {
            "url": url,
            "type": "GET",
            "datatype": "json"
        },
        "columns": [
            { "data": "city", "width": "10%" },            

//more code etc

1 Answer 1

1

Based on your method, you are missing some key content.

To ensure that the value passed by data-packageId can be accurately obtained in the js file, you need to add an id to the script that references the js file, and then obtain the passed value by obtaining the corresponding id in the js file:

  @section Scripts{
        <script  id="Index.js"  src="~/js/packageCity.js" data-packageId="@Model.Id"></script>
    }

js file:

$(document).ready(function () {
    var $vars = $('#Index\\.js').data();
    url = "/admin/packageCity/GetAll/" + $vars.packageid;
    loadDataTable();
});

And it should be noted that when obtaining the packageId through $vars, make sure that the packageId are all lowercase letters.

Another method:

You can create a variable in the view directly before referencing the js file, and then accept the value that needs to be passed, so that in the js file, you can directly call the variable to get the value that needs to be passed.

@section Scripts{
    <script> 
    var data = '@Model.Id'; 
    </script>
    <script  src="~/js/packageCity.js" ></script>

}

js file:

 $(document).ready(function () {

        url = "/admin/packageCity/GetAll/" + data;
        loadDataTable();
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.