RedirectToAction()NullReference异常ASP.NET MVC

时间:2017-04-24 17:06:04

标签: asp.net-mvc asp.net-mvc-4

我正在尝试使用RedirectToAction()将一个控制器中的一个操作发送一个字符串Id到另一个控制器中的另一个操作但是我一直得到一个空引用异常:

这是错误: 对象引用未设置为对象的实例。

我使用的RedirectToAction()方法:

return RedirectToAction("Index", "Assignments", new { cid = id.ToString() });

我得到的http请求:

HTTP:/本地主机:13501 /分配CID = CAIS132

而不是:

HTTP:/本地主机:13501 /约束/索引/ CAIS132 知道这是有效的

这是第一个动作:

//In Courses Controller
public ActionResult ManageCourse(object id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        return RedirectToAction("Index", "Assignments",new{cid=id.ToString()});
    }

这是我的另一个动作:

//In Assignments Controller
public ActionResult Index(string id)
    {
        //Some Model retrieval from database using the givin Id
        return View(model);
    }

这是我的RouteConfig.cs:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

当我使用它时:

return RedirectToAction("Index", "Assignments", id.ToString());

我使用NullReference获取此URL:

HTTP:/本地主机:13501 /约束长度= 7

Index操作中的id属性为null! 有什么想法吗?

修改

解: 感谢@nurdyguy,

“嗯,那么属性不是问题。你试图发送的对象没有定义的.toString()方法,这就是你得到System.Object ......的原因。这是因为你的id是对象id,而class对象的定义太松散了。你需要更具体地定义你的id变量。“

0 个答案:

没有答案
相关问题