0

In my View , and it's not working...

@model PASKAN.Web.Security.Models.User
<p class="lan-name"><label>Language</label>@Html.DropDownListFor(o => o.Language, Enum.GetValues(typeof(Enum)).Cast<Enum>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))</p>

my language Model is as follows

public enum Language {
    English = 0,
    Spanish=1,
    Latin =3
}

My controller looks like this

public ActionResult Edit()
{
    Models.User user = new User(Convert.ToInt32(User.Identity.Name));
    ViewBag.Languages = Enum.GetNames(typeof(Language)).ToList();
    return View (user);
}

1 Answer 1

2

You stuffed the languages in the ViewBag, so use them in your view:

@Html.DropDownListFor(o => o.Language, (IEnumerable<SelectListItem>)ViewBag.Languages)

but make sure that you have used the correct type that the helper expects:

public ActionResult Edit()
{
    Models.User user = new User(Convert.ToInt32(User.Identity.Name));
    ViewBag.Languages = Enum
        .GetNames(typeof(Language))
        .Select(x => new SelectListItem { Value = x, Text = x })
        .ToList();
    return View (user);
}

But since you mentioned something about a view model, I think you are misusing this term. In your case I can't see any trace of a view model. A view model would have looked like this:

public class MyViewModel
{
    public string Language { get; set; }
    public IEnumerable<SelectListItem> Languages { get; set; }
}

that your controller action would have passed to the view:

public ActionResult Edit()
{
    var user = new User(Convert.ToInt32(User.Identity.Name));
    var viewModel = new MyViewModel
    {
        Language = user.Language,
        Languages = Enum
            .GetNames(typeof(Language))
            .Select(x => new SelectListItem { Value = x, Text = x })
            .ToList()
    };
    return View (viewModel);
}

and in your strongly typed view:

@model MyViewModel
...
@Html.DropDownListFor(x => x.Language, Model.Languages)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.