Mvc3 Dropdownlistfor - a Simple Example

MVC3 DropDownListFor - a simple example?

You should do like this:

@Html.DropDownListFor(m => m.ContribType, 
new SelectList(Model.ContribTypeOptions,
"ContribId", "Value"))

Where:

m => m.ContribType

is a property where the result value will be.

Simple DropDownList in MVC3

The rule of thumb for getting values from the view back in the HTTPPOST for your object is to name the input controls id and name properties the same as the Models property name. An easy way to do this is to use Html helpers.

    public class Model
{
public Model()
{
List<SelectListItem> options = new List<SelectListItem>();
options.Add(new SelectListItem { Value = true.ToString(), Text = "yes" });
options.Add(new SelectListItem { Value = false.ToString(), Text = "no" });
ContinueOptions = options;
}
public bool Continue { get; set; }
public IEnumerable<SelectListItem> ContinueOptions { get; set; }
}

In your View:

@Html.DropDownListFor(m => Model.Continue, Model.ContinueOptions)

In your Controller:

[HttpPost]
public ActionResult Edit(Model model)
{
bool continueOn = model.Continue;

}

MVC3 dropdownlistfor

Just create a list of SelectListItem objects that contain the ratings, and then use Html.DropDownListFor with the rating stored in your model (Model.RATE).

@{
var ratings = new List<SelectListItem>();
for( var i = 0; i <= 10; i++ ) {
days.Add( new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.RATE == i } );
}
}
@Html.DropDownListFor( x => x.RATE, ratings )

Simple DropDownList in ASP.NET MVC3 app

Any particular reason why you don't want to use a ViewModel? They're very helpful for this type of problem.

If you don't want to use a ViewModel, then you can construct a specific class in your controller that is an aggregate of the properties you need from both classes:

public ActionResult Show(int id)
{
Course course = repository.GetCourse(id); // whatever your persistence logic is here
Project project = projectRepository.GetProjectByCourseId(id);
string CourseName = from c in course where
c.ID == project.courseID
select c.Name;
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
//add the selectList to your model here.
return View(); //add the model to your view and return it.
}

It would be far easier to have a ViewModel for this, so you could have a strongly typed view. Let me show you:

public class ProjectCourseViewModel
{
public SelectList ProjectCourseList {get; private set; }
public Project Project {get; private set; }
public Course Course {get; private set; }

public ProjectCourseViewModel(Project project, Course course)
{
ProjectCourseList = GetProjectCourseSelectList(project, course)
Project = project;
Course = course;
}

private SelectList GetProjectCourseSelectList(Project project, Course course)
{
IEnumerable<SelectListItem> selectList =
from c in course
select new SelectListItem
{
Selected = (c.ID == project.CourseId),
Text = c.Name,
Value = project.CourseId.ToString()
};
}

}

And then your controller would be really simple:

public ActionResult Show(int id)
{
Course course = repository.GetCourse(id);
Project project = projectRepository.GetProjectByCourseId(id);
ProjectCourseViewModel pcvm = new ProjectCourseViewModel(project, course)
return View(pcvm);
}

And then your view takes in a strongly typed model, and you don't have to rely on ViewData, which is a Good Thing.

Note: I haven't compiled this, just written it. There are probably compilation bugs.

MVC3 Simple drop down list

Make a model that contains a task and a list of methods.  Get all the methods and the task you want from db in your "custom" model. Pass the model into your view

Set in your view in the top @model NameProject.Folder.Modelname 

Then add to your view: 

List<SelectListItem> items = new List< SelectListItem>();

Foreach(var m in Model.Methods)  {
   items.Add(new SelectListItem{Value=@m.Id.toString() , Text=@m.MethodName}) 
}

 Then you could use html helpers that can help you bind model

@Html.DropDownListFor(model => Model.Task.Method, items)

In your controller that gets the post request use your model with task and methods as a parameter then just validate and savechanges

How to select an item from DropDownListFor list? (MVC3)

There are 2 properties in the Model.Countries list: the Text and the Value. So if you want to preselect a given item in the dropdown you should use the value:

@Html.DropDownListFor(
x => x.SelectedCountry,
new SelectList(Model.Countries, "Value", "Text", "us"),
"Please Select a Country"
)

which assumes that in Model.Countries you have an item with Value="us".

As an alternative you could do this inside the controller action that is returning the view:

public ActionResult Foo()
{
var model = new MyViewModel();
model.Countries = new[]
{
new SelectListItem { Value = "fr", Text = "France" },
new SelectListItem { Value = "uk", Text = "United Kingdom" },
new SelectListItem { Value = "us", Text = "United States" },
};
model.SelectedCountry = "us";
return View(model);
}

and in the view you could simply:

@Html.DropDownListFor(
x => x.SelectedCountry,
Model.Countries,
"Please Select a Country"
)

which will preselect the element with Value="us" (the third one in my example).

DropDownlistFor Creating New Entity with MVC3

I believe the mistake you're making is using your domain models in the view and assuming that on post the entire model should be completely binded and ready to store in the database. While it is possible to use domain models in the view, it's better practice to create separate View Models.

For example :

public class ApplicationViewModel
{
public int Id { get; set; }
public string Name { get; set; }

public SelectList ApplicationTypeList { get; set; }
public string ApplicationTypeId { get; set; }
}

In your view:

@Html.DropDownListFor(model => model.ApplicationTypeId, Model.ApplicationTypeList , "Choose...")

In your controller

[HttpPost]
public ActionResult Create(ApplicationViewModel model)
{
if (ModelState.IsValid)
{
Application application = new Application()
{
Id = model.Id,
Name = model.Name,
ApplicationType = db.ApplicationTypes
.First(a => a.Id == model.ApplicationTypeId);

};
db.Applications.Add(application);
db.SaveChanges();
return RedirectToAction("Index");
}

return View(model);
}

You can then make verifying that your View Model's ApplicationTypeId corresponds to a real application type part of your modelstate's verification. You can use AutoMapper to speed up the process of converting view models to domain models.

Understanding how DropDownListFor is working in MVC3


I want a user to be able to select a rule from the dropdownlist, and depending upon which rule was selected, I would like a label on the page to show the rule name (without posting)

You will need javascript here. jQuery would be perfect for the job. I would start by providing a deterministic id for the dropdown because if you run this view inside a template there could be prefixes added to the id which would ruin our javascript id selectors (see below):

@Html.DropDownListFor(
x => x.D1K2N3CARules,
new SelectList(Model.D1K2N3CARules, "ID", "Rule"),
new { id = "ruleDdl" }
)

then provide some container which will receive the selected value:

<div id="ruleValue" />

and finally in a separate javascript file subscribe for the change event of the dropdown list and update the container with the selected value/text:

$(function() {
// subscribe for the change event of the dropdown
$('#ruleDdl').change(function() {
// get the selected text from the dropdown
var selectedText = $(this).find('option:selected').text();

// if you wanted the selected value you could:
// var selectedValue = $(this).val();

// show the value inside the container
$('#ruleValue').html(selectedText);
});
});

I also need to be able to send the selected rule onto the next page.

You could put your dropdown inside a form

@using (Html.BeginForm("NextPage", "Foo"))
{
@Html.DropDownListFor(
x => x.D1K2N3CARules,
new SelectList(Model.D1K2N3CARules, "ID","Rule")
)
<input type="submit" value="Go to the next page" />
}

and the NextPage controller action will receive the selected value.

Simple MVC DropDownListFor

you need to create a new List of SelectListItem. I normally then drop this in the ViewBag for things liek this because you don't want it back. Then bind it to your a DropDownListFor control, here's one I've done for times:

private IEnumerable<SelectListItem> PopulateTimes()
{
List<SelectListItem> timeList = new List<SelectListItem>();
for (int count = 0; count < 24; count++)
{
timeList.Add(new SelectListItem()
{
Value = count.ToString("00"),
Text = count.ToString("00") + ":00",
Selected = count == 9,
});
}
return timeList;
}

then

ViewBag.DepartureTimes = PopulateTimes();

Then

@Html.DropDownListFor(model => model.DepartureTime, (IEnumerable<SelectListItem>)ViewBag.DepartureTimes)

Creating a dropdownlist c# mvc3


Html.DropDownList("Status", 
new SelectListItem[]{ new SelectListItem{ Text= "Showing", Value="Showing"},
//same for others
});


Related Topics



Leave a reply



Submit