0

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?

7
  • There are a few things possibly wrong here. What error are you getting? Commented Jan 26, 2016 at 21:23
  • @MikeC The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Commented Jan 26, 2016 at 21:26
  • Is it other ways to do it then? I mean using @Url.Action in JS in <a href.. Commented Jan 26, 2016 at 21:28
  • Okay, sounds like there's a bit of a misunderstanding about how to get your data then. You need to create a web API endpoint then gives you the data you need. Then your AJAX call needs to point to that endpoint. Finally, don't use new { id = cars.Id }, that's C# syntax. Assign the ID just like you would if you wrote the HTML by hand. Commented Jan 26, 2016 at 21:28
  • @MikeC Thank you. I'll look at it. Commented Jan 26, 2016 at 21:42

1 Answer 1

1

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(''));
    }
})
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.