locked
How to access ViewData from external javascript ? RRS feed

  • Question

  • User-79977429 posted

    Hi

    i've use this external javascript function to access ViewData variable(s) :

    function deleteOrderItem(orderID) {
        if (confirm('Are you sure want to delete this item?')) {
            $.ajax({
                type: "POST",
                url: "DeleteOrder",
                data: { id: orderID },
                success: function () {
                    setTimeout(function () {
                        debugger;
                        var personID = "@ViewData['_personID']";
                        viewItem(personID);
                    }, 500)
                }
            });
        }
    }

    But at runTime, when i'm using developer tools, the personID contains @ViewData[_personID] as text and not accessing real viewData which i've set in my action method!

    Here is my action method :

    // POST: Orders/Delete/5
            [HttpPost]
            public async Task<IActionResult> DeleteOrder(int id)
            {
                var orders = await _dbContext.Orders.FindAsync(id);
    
                ViewData["_personID"] = orders.PersonId;
    
                _dbContext.Orders.Remove(orders);
                await _dbContext.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

    Where is the problem & how to solve it?

    Thanks in advance

    Saturday, April 25, 2020 10:32 PM

All replies

  • User-474980206 posted

    External JavaScript files are not processed by the razor view, so razor syntax is just ignored. Use a hidden field to pass the Id to the JavaScript.

    Sunday, April 26, 2020 2:11 AM
  • User-1955300613 posted

    To access ViewData from external javascript, you can create a JavaScript global variable and store the ViewData value in that global variable.

    Give you my sample:

    In external js file:

    console.log("ViewData Value:" + viewdataName);

    In .cshtml file:

    <head>
        <script type="text/javascript">
            var viewdataName = '@ViewData["Name"]';
        </script>
        <script src="~/ExternalJavaScript.js"></script>
    </head>

    Then the external data can access the ViewData,

    Hope this can give you some inspiration.

    Friday, May 29, 2020 6:05 AM
  • User-217098811 posted

    Hi

    hamed_1983

    Try to put your JavaScript code 

    var personaid = "@ viewdata ['_ personID']";

    replace with

    var personaid = "@ viewdata ["_ personID"]";

    Hope this can help you

    Best Regards

    Yinqiu

    Tuesday, June 2, 2020 3:32 AM