我是MVC的新手,当我尝试通过URL传递多个参数时,我正在努力解决路由问题。
来自包含网址的网页:/PersonCAFDetail/Index/3?memberid=4
...我正在尝试将Html.ActionLink设置为指向Create操作,使得id = 3且memberid = 4.
阅读了许多类似的帖子后,似乎以下内容应该有效:
@Html.ActionLink("Create New", "Create", null, new { memberid = "memberid" })
但是,这会导致创建URL如下:
<a href="/PersonCAFDetail/Create/3" memberid="memberid">Create New</a>
我的路线设置为:
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; }
}
}
答案 0 :(得分:11)
最后,您需要将两个参数传递给视图:
指数行动:
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+" }
);
答案 1 :(得分:0)
Html.ActionLink(string, string, object, object)
..是你正在使用的。这些参数如下:
Html.ActionLink(<link text>, <action name>, <route values>, <html attributes>
您将数据放入属性参数中,这自然会使它们成为您链接的属性(而不是路由值)。
用法示例:
@Html.ActionLink("Create new", "Create", new { id = Model.cafID, memberid = Model.personID }, null);
答案 2 :(得分:0)
因为您的Url.Action不起作用是&amp; url中的char已编码,因此您必须使用
@Html.Raw(Html.ActionLink("Create New", "Create", "PersonCAFDetail", new { id=ViewBag.cafID , memberid =ViewBag.personID}, null))
现在,它正在运作;)
答案 3 :(得分:0)
您应该创建一个具有重载方法的ActionLink
MvcHtmlString HtmlHelper.ActionLink(
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes
)
您的情况:
@Html.ActionLink("Create New", "Create", PersonCAFDetail, new { id = "id", memberid = "memberid" })