1

I have a view with a form. On that form I have some textboxes and 2 dropdownlists.

This is my ViewModel.

public class NewApplicationViewModel
{
    public ApplicationData Application { get; set; }

    //Selectlists
    public SelectList Questionnaires { get; set; }
    public SelectList Jobs { get; set; }
}

The ApplicatoinData class looks like this

    public class ApplicationData
{
    [HiddenInput(DisplayValue = false)]
    public Guid Id { get; set; }
    [Required]
    public ApplicantData Applicant { get; set; }
    [Required]
    public QuestionnaireData Questionnaire { get; set; }
    [Required]
    public JobData Job { get; set; }
    public string Pdf { get; set; }
}

The "Questionnaire" and te "Job" have to be selected from the dropdownlists. How can a bind the selected value in the dropdown to the object in my "ApplicationData"? To be complete, this is my controller action to hande the form submit.

    [HttpPost]
    public ActionResult NewApplication([Bind(Prefix="Application")]ApplicationData model)
    {
        var application = Mapper.Map<ApplicationData, Application>(model);
        _applicationRepository.Add(application);
        _session.Commit();
        return View();
    }

Thanks

1
  • You can specify the selected value of SelectList when you create the NewApplicationViewModel instance. Commented Mar 9, 2012 at 8:51

2 Answers 2

3
@Html.DropdownListFor(
    x => x.Application.Questionnaire.ID,
    Model.Questionnaires
)

@Html.DropdownListFor(
    x => x.Application.Job.ID,
    Model.Jobs
)
Sign up to request clarification or add additional context in comments.

Comments

1

Please refer below link for the bind drop down list. It will be very helpful to you.

ASP.NET MVC - drop down list selection - partial views and model binding

Can't get selected drop down value to bind to view model property

Here if you do not want to create property in model for the List of items, than you can also store it in a ViewData or ViewBag. Please find sample code below.

<%= Html.DropDownList("Category.CategoryId", new SelectList((
IEnumerable<ProductManagement.Models.Category>)ViewData["CategoryList"],
"CategoryId", "CategoryName"))%>

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.