DropDownListFor not pre-selecting value from model - c#

Controller Code:
AccountsDetailsViewModel vOwnerVM = Mapper.Map<VehicleOwner, AccountsDetailsViewModel>(vOwner);
AccountsDetailsAccountViewModel vOwnerDetailsVM = Mapper.Map<VehicleOwner, AccountsDetailsAccountViewModel>(vOwner);
ViewBag.FleetType = new SelectList(VehicleOwnerFleetTypeFactory.GetTypes().OrderBy(l => l.Type), "Id", "Type");
vOwnerVM.AccountDetails = vOwnerDetailsVM;
Main ViewModel Code:
public class AccountsDetailsViewModel
{
public AccountsDetailsAccountViewModel AccountDetails { get; set; }
}
Main View Code
#model X.Views.Accounts.ViewModels.AccountsDetailsViewModel
#Html.Partial("DetailsAccount", #Model.AccountDetails)
Partial ViewModel Code:
[DisplayName("Fleet Type")]
public int FleetType { get; set; }
Partial View Code
#model X.Views.Accounts.ViewModels.AccountsDetailsAccountViewModel
#Html.DropDownListFor(model => model.FleetType,
(IEnumerable<SelectListItem>)ViewBag.FleetType)
#Html.DisplayFor(model => model.FleetType) (FOR DEBUG)
VehicleOwnerFleetType class
public class VehicleOwnerFleetType
{
public int Id { get; set; }
public string Type { get; set; }
}
public class VehicleOwnerFleetTypeFactory
{
static readonly VehicleOwnerFleetType[] Types = new VehicleOwnerFleetType[] {
new VehicleOwnerFleetType() {Id = 0, Type = "Unknown"},
new VehicleOwnerFleetType() {Id = 1, Type = "HGV"},
new VehicleOwnerFleetType() {Id = 2, Type = "Car"},
new VehicleOwnerFleetType() {Id = 3, Type = "Van"},
new VehicleOwnerFleetType() {Id = 4, Type = "Mixed"}
};
public static VehicleOwnerFleetType[] GetTypes()
{
return Types;
}
public static VehicleOwnerFleetType GetType(int id)
{
return Types.FirstOrDefault(m => m.Id == id);
}
}
Regardless of what the database shows, the dropdown does not display the correct value from the model, only ever the top value in the list.
However if I select a value and then submit the form to save the changes to the database, it does submit the correct value.
When returning the view of the viewmodel in the controller, the values mirror the database exactly, I cannot figure out why it is doing this.
Edit: The 'Sectors' dropdown is the ONLY one that auto-selects the correct value.

The problem is likely caused by the fact that your selectlist, and your VM's member variable have the same names.
model.FleetType
and
(IEnumerable<SelectListItem>)ViewBag.FleetType
Try to rename the select list to FleetTypeList or similar

Works fine for me. Check if you pass the model to the view.
#using WebApplication2.Controllers
#model WebApplication2.Controllers.MyModel
#{
ViewBag.Title = "Home Page";
ViewBag.FleetType = new SelectList(
VehicleOwnerFleetTypeFactory.GetTypes().OrderBy(l => l.Type),
"Id",
"Type");
}
<div>
<h2>---------------------------</h2>
#Html.DropDownListFor(model => model.FleetType,
(SelectList)ViewBag.FleetType)
<h2>---------------------------</h2>
</div>
and
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyModel { FleetType = 2 });
}
}
public class MyModel
{
public int FleetType { get; set; }
}
public class VehicleOwnerFleetTypeFactory
{
public static FleetType[] GetTypes()
{
return new[]
{
new FleetType {Id = 1, Type = "Type 1"},
new FleetType {Id = 2, Type = "Type 2"},
new FleetType {Id = 3, Type = "Type 3"}
};
}
}
public class FleetType
{
public int Id { get; set; }
public string Type { get; set; }
}
}

Related

Create drop down list from List ASP.NET MVC

I have strongly typed view model and in one of class object I am passing list of options that I need to present in #html.Dropdownlist
View Model
public class CreateCampaign_VM
{
public MarketingCampaign MarketingCampaign { get; set; }
public List<MarketingCampaignType> MarketingCampaignType { get; set; }
}
Controller method
private CreateCampaign_VM GetCampaignObject()
{
CreateCampaign_VM _CampaignObject = new CreateCampaign_VM();
_CampaignObject.MarketingCampaignType.Add(new MarketingCampaignType {
CampaignTypeID = 1,
CampaignTypeTitle = "Email",
Description = "Email"
});
_CampaignObject.MarketingCampaignType.Add(new MarketingCampaignType
{
CampaignTypeID = 2,
CampaignTypeTitle = "Text",
Description = "Text"
});
_CampaignObject.MarketingCampaignType.Add(new MarketingCampaignType
{
CampaignTypeID = 3,
CampaignTypeTitle = "Post",
Description = "Post"
});
return _CampaignObject;
}
...
public ActionResult CreateCampaign_Title()
{
return PartialView("CreateCampaign_Title_Partial", GetCampaignObject());
}
Razor view
#model App.Business.Entities.CreateCampaign_VM
#using (Html.BeginForm("CreateCampaign_Title", "Campaign", FormMethod.Post, new { id = "CreateCampaignTitleForm" }))
{
.....
#Html.DropDownListFor(// 'MarketingCampaignType object' need help here
//...
}
Try this:
#Html.DropDownListFor(m => m.MarketingCampaign , new SelectList(Model.MarketingCampaignType, "CampaignTypeTitle", "CampaignTypeId"), new { id = "yourElementIdIfAny", #class = "yourClassNameIfAny" })

DropDownListFor from Simple List Model

How can i implement simple DropDownList without Id.
public AddItemModel()
{
Types = new SelectList(new []{"Type1", "Type2", "Type3"});
}
public SelectList Types { get; set; }
#Html.DropDownListFor(x => x.AddItem, ???
You will need a property on your view model to hold the selected value and then you may try this:
public AddItemModel()
{
var data = new [] { "Type1", "Type2", "Type3" };
Types = data.Select(x => new SelectListItem
{
Value = x,
Text = x,
});
}
public IEnumerable<SelectListItem> Types { get; set; }
public string SelectedType { get; set; }
and then in your view:
#Html.DropDownListFor(x => x.SelectedType, Model.Types)

MVC SelectLists using ViewBag SelectedItem not being set

I have the following code:
public class OrganisationController : Controller
{
//
// GET: /Organisation/
public ActionResult Update()
{
var fisherman = new RoleType {Id = 1, Name = "Fisherman"};
var manager = new RoleType {Id = 2, Name = "Manager"};
var deckhand = new RoleType {Id = 3, Name = "Deckhand"};
var roleTypes = new List<RoleType>
{
fisherman, manager, deckhand
};
ViewBag.Roles = new SelectList(roleTypes, "Id", "Name");
return View(
new Organisation
{
Name = "Fish Co.",
People = new List<Person>
{
new Person
{
Name = "Squid",
RoleType = fisherman
},
new Person
{
Name = "Michael",
RoleType = manager
},
new Person
{
Name = "John",
RoleType = deckhand
}
}
});
}
[HttpPost]
public ActionResult Update(Organisation org)
{
return View();
}
}
public class Organisation
{
public string Name { get; set; }
public IList<Person> People { get; set; }
}
public class Person
{
public string Name { get; set; }
public RoleType RoleType { get; set; }
}
public class RoleType
{
public int Id { get; set; }
public string Name { get; set; }
}
In Update.cshtml
#model Models.Organisation
<form action="" method="post" enctype="multipart/form-data">
#Html.EditorFor(x => x.Name)
#Html.EditorFor(x => x.People)
<input type="submit"/>
</form>
In the EditorTemplates Person.cshtml:
#model Models.Person
#Html.EditorFor(x => x.Name)
#if(Model != null)
{
#Html.DropDownListFor( x => x.RoleType.Id, (SelectList)ViewBag.Roles)
}
I was expecting to be able to get to a page where I can update the organisation name, the people names and their roles. The trouble is that I can't get the selected item to be set for the dropdowns. I thought x => x.RoleType.Id would do this for me.
Does anyone know how I can get this to work?
Try this constructor: SelectList Constructor (IEnumerable, String, String, Object)
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
Object selectedValue
)
Something like this:
#Html.DropDownListFor( x => x.RoleType.Id, new SelectList((List<RoleType>)ViewBag.Roles, "Id", "Name", Model.RoleType.Id))

Html.ListBoxFor not selecting Items

Firstly I'm using MVC 2.0. I am having trouble getting a selection with a Multiselect listbox on the postback to my controller. Here is my Code:
Model
public class TestModel
{
public MultiSelectList AvailableTestTypes { get; set; }
public List<TestType> SelectedTestTypes { get; set; }
}
public class TestType
{
public long Id { get; set; }
public string Name { get; set; }
public bool isActive { get; set; }
}
Controller
public ActionResult Index(TestModel model)
{
if (model == null) model = new TestModel();
List<TestType> testList = new List<TestType>()
{
new TestType() { Id = 1, Name = "TESTING", isActive = true },
new TestType() { Id = 2, Name = "TESTING2", isActive = true },
new TestType() { Id = 3, Name = "TESTING3", isActive = true }
};
model.AvailableTestTypes = testList; //TODO: Fetch From Repository
return View(model);
}
[HttpPost]
public ActionResult PostForm(TestModel model)
{
List<long> act = model.SelectedTestTypes != null ? model.SelectedTestTypes.Select(x => x.Id).ToList() : new List<long>();
View
<%= Model != null && Model.AvailableTestTypes != null ?
Html.ListBoxFor(x => x.SelectedTestTypes,
new MultiSelectList(Model.AvailableTestTypes, "Id", "Name", Model.SelectedTestTypes),
new { #id = "testListboxId", #class = "blah", #title = "title" }) : null%>
After the Post to the Controller my Selected List count is 0 no matter how many I choose...
What am I getting wrong here?
I tried a few different solutions such as
Challenges with selecting values in ListBoxFor
but nothing worked :(
The difference between your script and the example in the other script, is the fact that you're trying to bind to a List, instead of a int[].
When you want to populate a Multiselect Listbox, you will have to set a DataValueField and a DataTextfield, otherwise no value is set.
model.AvailableTestTypes = new MultiSelectList(testList, "Id", "Name);
Then try using this class:
public class TestModel
{
public MultiSelectList AvailableTestTypes { get; set; }
public int[] SelectedTestTypes { get; set; }
}
In your PostForm action, you can use the Ids to retrieve the TestTypes.

Html.DropDownlistFor selectedValue

Having a hard time getting this dropDownList to Bind. This is simply a list of states. The Model.State is "TX", but my dropdownlist is showing "AK", which is the first value in the list. Any thoughts?
<%: Html.DropDownListFor(
model => model.State,
new SelectList(
muniSynd.getStatecodesDropDown(),
"Value",
"Text",
Model.State.ToString().Trim()
)
)
%>
In my muniSynd class, which is a wrapper of my dataContext.....
public IList<StateCodeViewModel> getStatecodesDropDown()
{
var states = from p in this._MuniDc.Statecodes
select new StateCodeViewModel
{
Value = p.Statecode1.ToString().Trim(),
Text = p.Statecode1.ToString().Trim()
};
return states.ToList();
}
public class StateCodeViewModel
{
public string Value{get;set;}
public string Text{get;set;}
}
Im using LinqToSQL, here is the object
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Statecodes")]
public partial class Statecode
{
private string _Statecode1;
public Statecode()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="Statecode", Storage="_Statecode1", DbType="NVarChar(3)")]
public string Statecode1
{
get
{
return this._Statecode1;
}
set
{
if ((this._Statecode1 != value))
{
this._Statecode1 = value;
}
}
}
}
I've tried to replicate your problem, but my example below works fine:
public class HomeController : Controller
{
public ActionResult Index()
{
var viewModel = new IndexViewModel();
viewModel.State = "TX";
return this.View(viewModel);
}
public static IList<StateCodeViewModel> getStatecodesDropDown()
{
var stateCodes = new List<string> { "AX", "GH", "TX" };
var states = from p in stateCodes
select new StateCodeViewModel
{
Value = p,
Text = p
};
return states.ToList();
}
}
public class IndexViewModel
{
public string State { get; set; }
}
public class StateCodeViewModel
{
public string Value { get; set; }
public string Text { get; set; }
}
View
#using MVCWorkbench.Controllers
#model IndexViewModel
#{
ViewBag.Title = "title";
}
#Html.DropDownListFor(model => model.State,
new SelectList(HomeController.getStatecodesDropDown(),
"Value",
"Text",
Model.State.ToString().Trim()
)
)
Not sure what to suggest other then check that the State value is in the dropdown list. Also this could be a case-sensitivity issue perhaps?

Categories