嗨,我在尝试注册时遇到了问题。 这是我的代码:
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'的空条目。可选参数必须是引用类型,可为空的类型,或者必须声明为可选参数。
请帮助:|
答案 0 :(得分:0)
根据您提供的代码,您的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请求。由于我们在查询字符串中显式传递了userId
参数,因此您的错误参数将正确填充值101
另一种选择是将操作方法参数名称更改为id
public ActionResult Profile(int id)
{
// to do : return something
}