Home > Net >  JS Function to navigate to the new View MVC C# not working
JS Function to navigate to the new View MVC C# not working

Time:09-23

This is my details page in controllers and wanting to click on the button and navigate to the detail page (eg. /ExpiationOffeces/Details/id)

   public async Task<IActionResult> Details(string id)
        {
            if (id == null || _context.ExpiationOffences == null)
            {
                return NotFound();
            }

            var expiationOffence = await _context.ExpiationOffences
                .FirstOrDefaultAsync(m => m.ExpiationOffenceCode == id);
            if (expiationOffence == null)
            {
                return NotFound();
            }

            return View(expiationOffence);
        }

And adding the JS function to run but it just shows (/ExpiationOffeces/Details), properly it's not working, my JS function

function foo(id) {
    window.location = "@Url.Action('Details', 'ExpiationOffences', new { id = '__id__'})"   id;
}

And my index view

<div >
        @foreach (var item in Model.Items)
        {
            <div >
                <div >
                    <div >
                        <h5 >Expiation Code: @item.ExpiationOffenceCode</h5>
                        <p >Expiation Offence Description: <br> @item.ExpiationOffenceDescription</p>
                        <a asp-action="Details" asp-route-id="@item.ExpiationOffenceCode"  target="_blank">View Detail</a>
                    </div>
                </div>
            </div>
        }
    </div>

What should I do to redirect to the detail page?

CodePudding user response:

Try the code like below:

<a onclick="foo(1)" >View Detail</a>

<script>
    //pass id in url
    function foo(id) {
        var url = '@Url.Action("Details", "ExpiationOffences", new {id = "_id" })';
        var urlWithId = url.replace('_id', id);
        window.location.href = urlWithId;
    }
</script>

result:

enter image description here

Besides, you can use asp-route-id

<a asp-action="Details" asp-route-id="@item.ExpiationOffenceCode">Details</a> |

You can have a look at Part 6, controller methods and views in ASP.NET Core and Routing to controller actions in ASP.NET Core to know more.

Update

id in detail page is string

Change the onclick like onclick="foo('@item.ExpiationOffenceCode')"

  • Related