通过BeginExecuteCore使用文化/语言的基本视图模型

时间:2013-08-09 07:42:15

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

我想知道是否有人可以帮助我吗?我正在尝试创建一个用户登录的站点,它从数据库中检索他们选择的语言,并在设置文化时使用它。还有许多关于用户的设置,可以与用户的语言同时检索。

文化/翻译是通过下面的基本控制器处理的(它仍然是一个测试版本,但你会得到这个想法)。

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而不仅仅是视图。我发现这里有一个有趣的帖子Pass data to layout that are common to all pages对我有用,我创建了一个基本的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。

感谢您提供任何帮助或指示!

1 个答案:

答案 0 :(得分:2)

确定。我终于解决了这个问题。

我正在创建一个我所有其他视图模型都将继承的基本模型。如果任何视图不需要自己的视图模型,也可以直接调用它。

public class ViewModelBase
{
    public UserSettings ProfileSettings;

    // Create a new instance, so we don't need to every time its called.
    public ViewModelBase()
    {
        ProfileSettings = new UserSettings();
    }

}

public class UserSettings // UserSettings is only used here and consumed by ViewModelBase, its the name there that is used throughout the application
{
    public string BrandName { get; set; }
    public UserRegistrationInformation UserSession;    
}

这是在basecontroller中生成的。

public abstract class BaseController : Controller
{
    public ViewModelBase vmb = new ViewModelBase();

    protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
    {
        string cultureName = null;
        int userid = 0;

        if (System.Web.Security.Membership.GetUser() != null)
        {
            //logged in
            userid = (int)System.Web.Security.Membership.GetUser().ProviderUserKey;

            WebUsersEntities db = new WebUsersEntities();
            vmb.ProfileSettings.UserSession = db.UserRegistrationInformations.Where(r => r.uri_UserID == userid).FirstOrDefault();
            vmb.ProfileSettings.BrandName = "test";

            cultureName = "es-es";
        }
        else
        {
            // not logged in                
            cultureName = Request.UserLanguages[0]; // obtain it from HTTP header AcceptLanguages
        }


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

其他控制器都从该控制器继承。如果任何屏幕具有专用的视图模型,它可以从控制器中填充的模型中检索信息,如下所示:

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        LoginModel v = new LoginModel();

        v.ProfileSettings = vmb.ProfileSettings;

        ViewBag.ReturnUrl = returnUrl;
        return View(v);
    }

我希望将来帮助某人。