无法通过JavaScript将参数从View传递到Controller
虽然我设法将网格的选定行ID发送到控制器,但是无法构建打开操作视图的URL(它是创建/ Controller / Action而不是/ Controller / Action / id 。所以,当我尝试打开视图时使用/ Controller / Action / id它已打开,但无法通过按钮单击打开,如下所示。
视图:
$('#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); } }) })
控制器:
// 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 } ); } }
是否有上面的另一个例子来传递参数或上面的代码是否有任何错误? 提前致谢。
使用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; });
希望这可以帮助。
.ToolBar(toolbar => { toolbar.Template(@ ); })
然后你将使用jQuery获取data-attribute。
$('.js-myKendoButton').attr('data-id');
更多信息: 如何在ASP.NET MVC中的HTML-5 data- *属性中使用破折号
使用这个,我希望这会对你有所帮助