简体   繁体   English

JavaScript中的ASP MVC URL操作

[英]ASP MVC URL Action in JavaScript

I have this on Razor page 我在剃刀页面上有这个

Index.cshtml 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. 我想使用Jquery Ajax在javascript中替换它。

$.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? 但是,我该怎么办?

Your ajax call appears odd. 您的ajax呼叫看起来很奇怪。 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 . 您告诉它获取/Cars/Home/{id} ,然后返回时,您正在创建许多/Cars/Home/{someId} (基于data的长度),但您不是真正使用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 (eg Car ), and then create all the links to the details page of each of that type, all using js. 我假设您想将HttpGet发送到/Cars/Home/ (不传递id ),并且我假设这将返回类型(例如Car )的IEnumerable (列表),然后创建指向的详细信息页面的所有链接每种类型,都使用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(''));
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM