从查看使用JavaScript不能传递参数给控制器控制器、参数、JavaScript

2023-09-11 00:58:42 作者:东京的樱花╰落满巴黎的街

虽然我管理网格的选定行ID发送到控制器,网址为打开动作视图不能建立(这是创建/控制器/ /行动,而不是控制器/动作/ ID 所以,当我尝试打开与该视图/控制器/动作/ ID 它是开放的,但它不能被点击按钮,如下打开。

Although I manage to send the grid's selected row id to the controller, the url for opening action view cannot be built up (it is created /Controller/Action instead of /Controller/Action/id. So, when I try to open the view with /Controller/Action/id it is open, but it cannot be opened by button click as below.

查看:

<input type="button" id="btn" name="name" value="send to Server!" />

<script>
$('#btn').click(function () {
    var items = {};
    var grid = $('#Grid').data('kendoGrid');
    var selectedElements = grid.select();
    var item = grid.dataItem(selectedElements[0]);

    $.ajax({
        type: "POST",
        data: item.ID, //I obtained the id properly
        url: '@Url.Action("CreateParticipant", "Training")',
        success: function (result) {
            //console.log(result);
        }
    })
})
</script>

控制器:

// GET: /Training/CreateParticipant/5
public ActionResult CreateParticipant(int? id)
{
    Training training = repository.Trainings.FirstOrDefault(m => m.ID == id);
    if (training == null)
    {
        return HttpNotFound();
    }
    var trainingParticipantViewModel = new TrainingParticipantViewModel(training);
    return View(trainingParticipantViewModel);
}

Route.config:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            //defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            defaults: new { controller = "Multiplier", action = "Index", id = UrlParameter.Optional }
        );
    }
}

难道还有其他例子如上面传递参数或者是那里的code以上任何错误?先谢谢了。

Is there another example as above to pass the parameters or is there any mistake on the code above? Thanks in advance.

推荐答案

Javascript的

Javascript

$('#btn').on("click",function () {
    var items = {};
    var grid = $('#Grid').data('kendoGrid');
    var selectedElements = grid.select();
    var item = grid.dataItem(selectedElements[0]);

        $.ajax({
            type: "GET",
            data: item.ID, //I obtained the id properly
            url: '@Url.Action("CreateParticipant", "Training")/'+item.ID,
            datatype:'html',
            success: function (result) {
              alert(result)
            }
        })
    })

或者使用

$('#btn').on("click",function () {
    var items = {};
    var grid = $('#Grid').data('kendoGrid');
    var selectedElements = grid.select();
    var item = grid.dataItem(selectedElements[0]);

    window.location.href= '@Url.Action("CreateParticipant", "Training")/'+item.ID; 
});

希望这有助于。

Hope this helps.