ASP.NET MVC将ActionLink中的字符串传递给控制器

时间:2013-05-30 08:14:00

标签: c# asp.net-mvc actionresult

将一个参数传递给控制器​​是空的..从我​​看到的使用正确的重载的例子。 任何有用的帮助

@{
foreach (string str in ViewBag.ServerNames)
{
    <ul> 
     <img src="../../Content/Images/my_computer.png" alt="Computer Name"/>
        <li >@Html.ActionLink(linkText: str.ToString(),actionName: "Index",controllerName:"Customer",
        routeValues:new{str = str.ToString()} , htmlAttributes: null)</li>
    </ul>

}

}

public ActionResult Index(string conName)
    {
        Response.Write("con name = " + conName);
        Response.End();
        string con = ConfigurationManager.ConnectionStrings[conName].ConnectionString;
        trakman_Entities db = new trakman_Entities(con);
        return View(db.customers.ToList());
    }

浏览器源代码

 <ul> 
     <img src="../../Content/Images/my_computer.png" alt="Computer Name"/>
        <li ><a href="/Customer/Index/DefaultConnection">DefaultConnection</a></li>
    </ul>
    <ul> 
     <img src="../../Content/Images/my_computer.png" alt="Computer Name"/>
        <li ><a href="/Customer/Index/trakman_Entities">trakman_Entities</a></li>
    </ul>
    <ul> 
     <img src="../../Content/Images/my_computer.png" alt="Computer Name"/>
        <li ><a href="/Customer/Index/trakman_Entities1">trakman_Entities1</a></li>
    </ul>

2 个答案:

答案 0 :(得分:6)

您应该在操作链接中提供正确的参数名称,此处无需指定参数:)

@{
foreach (string str in ViewBag.ServerNames)
{
    <ul> 
     <img src="../../Content/Images/my_computer.png" alt="Computer Name"/>
        <li >@Html.ActionLink(str.ToString(),"Index","Customer",
        new{conName= str.ToString()} , null)</li>
    </ul>

}

答案 1 :(得分:0)

如果您使用的是开箱即​​用的MVC,那么它只能使用一个名为id的参数来接受一个int。要完成这项工作,您需要在URL中明确定义参数,如下所示:

<a href="/Customer/Index/?conName=trakman_Entities">trakman_Entities</a>