繁体   English   中英

尝试在asp.net mvc中注册用户时出错

[英]Error When trying to Register a User in asp.net mvc

嗨,我在尝试注册时遇到了问题。 这是我的代码:

public ActionResult RegisterButton(Models.Users User)
    {
        using (MyDbContext db = new MyDbContext())
        {
            if (ModelState.IsValid == false)
            {
                return View("Register", User);
            }

            else
            {
                db.Users.Add(User);

                db.SaveChanges();
                Session["UserId"] = User.Id;
                //Directory.CreateDirectory(string.Format("~/App_Data/{0}",User.UserName+User.Id.ToString()));
                return RedirectToAction("Profile", "Profile",new { User.Id});
            }
        }
    }

这也是我的路由配置代码:

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 }
        );
    }

我得到这个错误: 参数字典在'DigiDaroo.Controllers.ProfileController'中为方法'System.Web.Mvc.ActionResult Profile(Int32)'包含非空类型'System.Int32'的参数'UserId'的空条目'。 可选参数必须是引用类型,可为空的类型,或者必须声明为可选参数。

请帮助:|

根据您提供的代码,您的RegisterButton方法将使用以下位置标头值将重定向响应返回到浏览器

/Profile/Profile/101

其中101替换为新用户记录的实际ID。 使用路由配置,如果您的操作方法参数名称为id ,则代码不会引发该错误消息。 由于您收到错误消息,因此我假设您的操作方法参数名称是其他名称。 因此,请确保您明确传递了routeValue对象。

例如,如果您的操作方法参数名称为userId例如

public ActionResult Profile(int userId)
{
    // to do : return something
}

您的重定向响应呼叫应如下所示

return RedirectToAction("Profile", "Profile",new { userId = User.Id});

这会将重定向响应的位置标头值作为/Profile/Profile?userId=101 ,浏览器将使用它发出GET请求。 由于我们在querystring中显式传递了userId参数,因此您的错误参数将正确填充值101

另一种选择是将操作方法​​参数名称更改为id

public ActionResult Profile(int id)
{
    // to do : return something
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM