我想知道是否有人可以帮助我?我正在尝试创建一个用户登录的站点,它从数据库中检索他们选择的语言,并在设置文化时使用它。还有一些关于用户的设置将与用户的语言同时被检索。
文化/翻译是通过下面的基本控制器处理的(它仍然是一个测试版本,但你会明白的)。
public abstract class BaseController : Controller
{
//public UserRegistrationInformation UserSession;
//public void GetUserInfo()
//{
// WebUsersEntities db = new WebUsersEntities();
// UserSession = db.UserRegistrationInformations.Where(r => r.uri_UserID == WebSecurity.CurrentUserId).FirstOrDefault();
//}
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
//GetUserInfo();
string cultureName = null;
// Change this to read from the user settings rather than a cookie
/// Attempt to read the culture cookie from Request
//HttpCookie cultureCookie = Request.Cookies["_culture"];
//if (cultureCookie != null)
// cultureName = cultureCookie.Value;
//else
cultureName = Request.UserLanguages[0]; // obtain it from HTTP header AcceptLanguages
//cultureName = "es-es";
// Validate culture name
cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
}
这主要取自http://afana.me/post/aspnet-mvc-internationalization-part-2.aspx
我一直在寻找如何将用户的设置传递给 _layout 而不仅仅是视图。我在这里找到了一篇有趣的帖子,将数据传递给所有适用于我的页面共有的布局,我创建了一个基本 ViewModel,并且任何其他 ViewModel 都在继承它。
public abstract class ViewModelBase
{
public string BrandName { get; set; }
public UserRegistrationInformation UserSession;
public void GetUserInfo()
{
WebUsersEntities db = new WebUsersEntities();
UserSession = db.UserRegistrationInformations.Where(r => r.uri_UserID == WebSecurity.CurrentUserId).FirstOrDefault();
}
}
为了进行测试,我将现有的更改密码模型和控制更改为:
public class LocalPasswordModel : ViewModelBase
{..........}
和
public ActionResult Manage(ManageMessageId? message)
{
//ViewModelAccounts vma = new ViewModelAccounts();
//vma.GetUserInfo();
LocalPasswordModel l = new LocalPasswordModel();
l.GetUserInfo();
l.BrandName = "blue";
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Manage");
return View(l);
}
这再次完美运行,但是我只想检索一次用户的信息。目前我可以通过在 BeginExecuteCore 中调用它来做我想做的事,然后再在上面的控制器中调用它。我怎么能把它称为一次在任何地方都可以使用?即填充BaseViewModel。
感谢您提供的任何帮助或指示!