将多个参数从url传递到html.actionlink

我是MVC的新手,当我尝试通过URL传递多个参数时,我正在努力使用路由。

从包含URL的页面: /PersonCAFDetail/Index/3?memberid=4

…我正在尝试将Html.ActionLink设置为指向Create操作,使得id = 3且memberid = 4。

阅读了许多类似的post后,似乎以下内容应该有效:

 @Html.ActionLink("Create New", "Create", null, new { memberid = "memberid" }) 

但是,这会导致URL创建如下:

 Create New 

我有一条路线设置为:

  routes.MapRoute( name: "PersonCAFDetail", url: "PersonCAFDetail/Create/{id}/{memberid}", defaults: new { controller = "PersonCAFDetail", action = "Create", id = "@\d+", memberid = @"\d+" } ); 

控制器接受两个参数,如下所示:

  public ActionResult Create(int id, int memberid) { int cafID = id; int personID = memberid; ViewBag.detailTypeID = new SelectList(db.tCAFDetailTypes, "detailTypeID", "detailType"); ViewBag.cafID = new SelectList(db.tFamilyCAFs, "cafID", "issues"); ViewBag.personID = new SelectList(db.tPersons, "personID", "forename"); return View(); } 

任何帮助赞赏。

——-编辑模型———-

 namespace WhatWorks.Models { using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations; public partial class tPersonCAFDetail { [Key, HiddenInput(DisplayValue=false)] public int cafID { get; set; } [Key, HiddenInput(DisplayValue = false)] public int personID { get; set; } [Key, HiddenInput(DisplayValue = false)] public int detailTypeID { get; set; } [Required, DataType(DataType.MultilineText)] public string notes { get; set; } public string FullName { get { return tPerson.forename + " " + tPerson.surname; } } public virtual tCAFDetailType tCAFDetailType { get; set; } public virtual tFamilyCAF tFamilyCAF { get; set; } public virtual tPerson tPerson { get; set; } } } 

最后,您需要将两个参数传递给视图:

指数行动:

 public ActionResult Index(int id, int memberid) { ... ViewBag.cafID = id; ViewBag.personID = memberid; return View(); } 

Index.cshtml

 @Html.ActionLink("Create New", "Create", "PersonCAFDetail", new { id=ViewBag.cafID , memberid =ViewBag.personID}, null) 

并检查您的路线语法… id = @“\ d +”

  routes.MapRoute( name: "PersonCAFDetail", url: "PersonCAFDetail/Create/{id}/{memberid}", defaults: new { controller = "PersonCAFDetail", action = "Create", id = @"\d+", memberid = @"\d+" } ); 
 Html.ActionLink(string, string, object, object) 

..是你正在使用的。 这些参数如下:

 Html.ActionLink(, , ,  

您将数据放入attributes参数中,这自然会使它们成为链接的属性(而不是它们的路由值)。

用法示例:

 @Html.ActionLink("Create new", "Create", new { id = Model.cafID, memberid = Model.personID }, null); 

导致您的Url.Action不起作用的是url中的&char已编码,因此您必须使用

 @Html.Raw(Html.ActionLink("Create New", "Create", "PersonCAFDetail", new { id=ViewBag.cafID , memberid =ViewBag.personID}, null)) 

现在,它正在工作;)