ASP.NET - 为什么 - 传递字符串时的ActionResult参数回来总是空? [英] ASP.NET - ActionResult parameter is coming back null always when passing string - why?

查看:263
本文介绍了ASP.NET - 为什么 - 传递字符串时的ActionResult参数回来总是空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始接触我的ASP.NET MVC项目类型的第一个项目,我创建一个详细页面,而不是传递的模板(INT ID),我想传递一个字符串代替。但是,当我在调试模式,并在URL输入该的myString为null。为什么这样?我一定要改变别的somehwere别的吗?

所以,如果我去的网址,并输入以下内容:

<一个href=\"http://localhost:2345/Bank/EmployeeDetails/3d34xyz\">http://localhost:2345/Bank/EmployeeDetails/3d34xyz

 公众的ActionResult EmployeeDetails(字符串MyString的)// MyString的是空
{
     返回查看();
}


解决方案

在您的Global.asax.cs 文件,你将不得不默认情况下映射以下路线:

  routes.mapRoute(
    默认,
    {控制器} / {行动} / {ID}
    新{控制器=家,行动=索引,ID = NULL});

这意味着,如 HTTP URL时://本地主机:2345 /银行/ EmployeeDetails / 3d34xyz 将转到银行控制器, EmployeeDetails 行动,并传递值 3d34xyz 到一个名为 id参数。这是完全好吧传递一个字符串,但为了使其工作,你有两个选择:

1)可变重命名为在你的操作方法标识

 公众的ActionResult EmployeeDetails(字符串ID){...}

2)添加你想为你的字符串的任何名称匹配另一条路线。请务必使它比默认路由更加具体,并把它的的在的Global.asax.cs 文件的缺省路由。

  routes.mapRoute(
    BankEmployeeDetails
    银行/ EmployeeDetails / {}的myString
    新{控制器=银行,行动=EmployeeDetails的myString = NULL});

这将通过的myString 默认值,如果没有值在传递的url,但与该URL指定你会通过值 3d34xyz

I am barely starting out with my first project on the ASP.NET MVC project type and I am creating a Details page where instead of passing the templated (int id), I would like to pass a string instead. But when I am in debug mode, and enter this in the URL, "myString" is null. Why so? Do I have to change anything else somehwere else?

So if I go to the URL and enter this:

http://localhost:2345/Bank/EmployeeDetails/3d34xyz

public ActionResult EmployeeDetails(string myString) // myString is null
{
     return View();
}

解决方案

In you Global.asax.cs file, you will have the following route mapped by default:

routes.mapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = null });

That means that an url like http://localhost:2345/Bank/EmployeeDetails/3d34xyz will go to the Bank controller, the EmployeeDetails action and pass the value 3d34xyz into a parameter named id. It is perfectly allright to pass a string, but in order to make it work you have two options:

1) Rename the variable to id in your action method.

public ActionResult EmployeeDetails(string id) { ... }

2) Add another route that matches whatever name you want for your string. Make sure to make it more specific than the default route, and to place it before the default route in the Global.asax.cs file.

routes.mapRoute(
    "BankEmployeeDetails"
    "Bank/EmployeeDetails/{myString}"
    new { controller = "Bank", action = "EmployeeDetails", myString = null });

This will pass a default value of null to myString if no value is passed in the url, but with the url you specified you will pass the value 3d34xyz.

这篇关于ASP.NET - 为什么 - 传递字符串时的ActionResult参数回来总是空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆