سؤال

It's been a while since I visited StackOverflow...

So, i've started using ASP.NET MVC4 with Razor, using a Model-first approach to Entity Framework. So far i've liked it , althoug I have had problems remembering certain stuff.

For example, now i'm trying to implement a simple Login form, that includes Username + Password + UserType. However, as I recall from my experiences from MVC3, you cannot pass along two models... unless you use a Tuple.

So, my objective is to create the form via @HTML helpers, but the only one i've been unable to use is the DropdownListFor, that would bring forth the list of User Types and apply them in the form.

@model Tuple<EMS_v1.User, EMS_v1.UserType>
@{
ViewBag.Title = "Log in";
}

<section id="loginForm">
<h2>Use a local account to log in.</h2>
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Log in Form</legend>
    <ol>
        <li>
            @Html.Label(" User Name")
            @Html.TextBoxFor(m => m.Item1.User_Name)
            @Html.ValidationMessageFor(m => m.Item1.User_Name)
        </li>
        <li>
            @Html.Label("Password")
            @Html.PasswordFor(m => m.Item1.User_Pass)
            @Html.ValidationMessageFor(m => m.Item1.User_Pass)
        </li>
        <li>
            @Html.Label("Portal Access")
      >>>>> @Html.DropDownListFor(model => model.Item2.Type_Id, new SelectList(Model.Item2, "Type_Id", "Description"));
        </li>
    </ol>
    <input type="submit" value="Log in" />
</fieldset>
}
</section>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

My Entity Framework Model includes UserType (int Type_Id, String Description) and User (int Id, String User_Name, String User_Pass, UserTypeType_Id), being UserTypeType_Id a Foreign Key that refers back to UserType table.

Is there any way to generate the list or IEnumerable from the UserType table? because I'm sure the code I posted doesn't work properly.

هل كانت مفيدة؟

المحلول

Create a collection in the action method of controller and assign it to some Viewbag property e.g ViewBag.UserType = new SelectList();

this collection should be IEnumerable type object.

Now use this ViewBag prorety from view.

e.g. @Html.DropDownList ("UserType" , "Select User Type")

نصائح أخرى

You really shouldn't be using the Entity Framework entities in your views. Create a viewmodel for example:

public class LoginViewModel
{
    public string Username{get;set;}
    public string Password{get;set;}
    public int UserTypeId{get;set;}
    public IEnumerable<UserTypes> UserTypes{get;set;}
}

Then in your dropdown:

@Html.DropDownListFor(m => m.UserTypeId, Model.UserTypes.Select(t => new SelectListItem { Value = t.TypeId.ToString(), Text = t.Description }));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top