簡體   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