您的位置:首页 > 其它

MVC传递多个参数的两种方法

2010-04-18 23:53 176 查看
在今天的MVC测试中,我想在路由中传递多个参数,比如 Blog/Archtive/2010-04-18/4.html,参数是两个,一个是时间:2010-04-18,一个是序号:4。

经过一天的验证测试,最后终于找到了解决方案,并且还验证出了两种方案(赞一个^_^ ),由于初学MVC,测试中遇到了不少的问题,尤其是第一种方案的测试,开始的思路就是想采用多参数的URL,但不知道怎么回事,验证了一上午也没有通过,没办法只得去寻求其他解决方案,当我用第二种方案验证通过后,重新回到第一种方案的测试,竟然验证通过了,真不知道上午测试时哪个地方没有设置好,害的我还以为最初的想法行不通那!不说了,赶快将结果共享给大家,希望对大家有所帮助。

第一种方法:

1)添加路由表为:

   routes.MapRoute(
"Default", // Route name
"{controller}/{action}.html/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);

   routes.MapRoute("BlogActive",
"Blog/Archtive/{date}/{id}",
new { controller = "Blog", action = "Archtive" },
new {date = @"\d{4}-\d{2}-\d{2}"});

2)在View->Home文件中的Index.aspx文件有以下链接:
<li><%= Html.ActionLink("我的链接","Archtive/2010-04-18/4","Blog")%></li>
3)在Controllers->BlogController.cs中增加函数:

public ActionResult Archtive(string date, string id)
{
ViewData["date"] = date;
ViewData["id"] = id;
return View("Archtive");
}

4)在View->Blog文件夹中的Archtive.aspx文件中增加以下内容:

要查询的日志时间为:<%= ViewData["date"] %><br />
要查询的日志ID为:<%= ViewData["id"] %><br />

5)输入网址:http://localhost/MVCTest/Home/Index.html,页面中出现如下链接: http://localhost/MVCTest/Blog/Archtive/2010-04-18/4.html
6)点击页面中的链接,在http://localhost/MVCTest/Blog/Archtive/2010-04-18/4.html,页面中将呈现以下内容:

  要查询的日志时间为:2010-04-18
  要查询的日志ID为:4.html

  以上说明路由正确的得到了传入的两个参数。

第二种方法:
 1)在路由表中增加:

routes.MapRoute("BlogActive",
"Blog/Archtive/{*id}",
new { controller = "Blog", action = "Archtive" }

);

2)在View->Home文件中的Index.aspx文件有以下链接:
<li><%= Html.ActionLink("我的链接","Archtive/2010-04-18/4","Blog")%></li>

3)在Controllers->BlogController.cs中增加函数:
public ActionResult Archtive(string id)
{
ViewData["date"] = id;
return View("Archtive");
}

4)在View->Blog文件夹中的Archtive.aspx文件中增加以下内容:
要查询的日志时间为:<%= ViewData["date"] %><br />

5)输入网址:http://localhost/MVCTest/Home/Index.html,页面中出现如下链接:http://localhost/MVCTest/Blog/Archtive/2010-04-18/4.html

6)点击页面中的链接,在http://localhost/MVCTest/Blog/Archtive/2010-04-18/4.html页面中将呈现以下内容:

  要查询的日志时间为:2010-04-18/4.html
以上说明路由正确的得到了传入的参数,但这种方式其实是将2010-04-18/4.html作为一个参数传递过去,要想得到想要的两个参数的结果,还需要进一步解析方可使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: