0

I have a <select> element on a Razor view. It renders as a drop box with language values. I set language via custom cookies and a custom cookie aware view engine.

Let's say I have a cookie set (called language). I want to have a view render with a corresponding <option> marked as selected based on a cookie value. How can I control it with Razor?

1 Answer 1

1

Well I would put the select in a strongly typed partial view:

@inherits System.Web.Mvc.WebViewPage<Language>
@Html.DropDownListFor(x => x,
                    new SelectList((List<Language>)ViewBag.AllLanguages,
                    "Id",
                    "Text",
                    Model==null?-1:Model.Id), "Choose Language")

I would actually set the value in my controller

public virtual ActionResult _MyAction()
{
    // get users language
    string selectedLanguage = "English"; // default
    if(Request.Cookies["language"] != null)
    {
        selectedLanguage = Request.Cookies["lang"].ToString();
    }

    // language list
    ViewBag.AllLanguages = context.Languages.ToList();

    // retrieve language from database - example using EF
    ViewBag.SelectedLanguage = context.Languages
                                      .FirstOrDefault(l=>l.Text==selectedLanguage);

and then in my main view

@Html.Partial("LanguageSelect", ViewBag.SelectedLanguage);

This keeps the logic of what language to select away from the presentation of the actual select list. And you could put all that logic in a shared method if it's used a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.