Gunnar
Gunnar

Reputation: 89

ASP MVC URL Action in JavaScript

I have this on Razor page

Index.cshtml

 @for (int i = 0; i < Model.Count(); i++)
 {
 var cars = Model.ElementAt(i); 
 <a href="@Url.Action("Cars","Home", new { id = cars.Id })">
 }

And I want to replace this in javascript using Jquery Ajax.

$.ajax({
    type: "Get",
    url: '/Cars/Home',
    data: {
        id: $(this).attr("id")
    },
    dataType: "json",
    success: function (data) {             
        for (var i = 0; i < data.length; i++) {

            html1.push("<a href='Cars/Home', new { id = cars.Id })>");
            html1.push("</a>");
        }
        $("#wraps").html(html1.join(""));
    }
})

This give me an error. However, how can I do this thing?

Upvotes: 0

Views: 700

Answers (1)

Frank Fajardo
Frank Fajardo

Reputation: 7359

Your ajax call appears odd. You are telling it to get /Cars/Home/{id}, and then when it returns, you are creating a number of links to /Cars/Home/{someId} (based on the length of data), but you are not really using the content of data.

I assume you want to send an HttpGet to /Cars/Home/ (without passing an id), and I assume this returns an IEnumerable (list) of a type (e.g. Car), and then create all the links to the details page of each of that type, all using js. If so, you could do this:

$.ajax({
    type: 'GET',
    url: '/Cars/Home',
    dataType: 'json',
    success: function (data) {             
        var links = [];
        for (var i = 0; i < data.length; i++) {
            var car = data[i];                
            links.push("<a href='/Cars/Home/" + car.Id + "'>Link to Car Id " + car.Id + "</a>");
        }
        $("#wraps").html(links.join(''));
    }
})

Upvotes: 1

Related Questions