SelectList Selected Value Issue

720 views Asked by At

I have some code, the second of which works and the first doesn't. The idea is that the user has selected a site, and then it shows the information for this site, selecting a site automatically submits the form.

NOTE: I don't need the second one, I just did it to try and work out why the former wasn't working

ViewModel

public class SitesViewModel
{
    public SitesViewModel()
    {
        int allowMaintainSites = SessionWrapper.AllowMaintainSites.HasValue ? SessionWrapper.AllowMaintainSites.Value : 0;
        this.isAllowedMaintain = allowMaintainSites == 1;

    }
    public SelectList companySelectList { get; set; }
    public SelectList siteSelectList { get; set; }
    public SelectList siteSelectList1 { get; set; }
    public SelectList siteTypeSelectList { get; set; }
    public bool isAllowedMaintain { get; set; }
    public bool isAllowedSuper { get; set; }
    public bool companySelected { get; set; }
    public bool siteSelected { get; set; }
    public bool hasSites { get; set; }
    public int? currentSite { get; set; }
    public int? companyId { get; set; }
    public Site site { get; set; }
    public Site site1 { get; set; }
}

Controller:

[HttpGet()]
public ActionResult Sites()
{
    var viewModel = new SitesViewModel();
    viewModel.companySelectList = viewModel.isAllowedMaintain ?
            new SelectList(context.GetCompaniesAll(), "companyId", "name") :
            new SelectList(context.GetCompaniesByUser(SessionWrapper.UserId.Value), "companyId",  "name");
        return View(viewModel);
}
[HttpPost()]
public ActionResult Sites(string data)
{
    var viewModel = new SitesViewModel();
    if (Request["company"] != null)
    {
        int? companyId = stringToNullInt(Request["company"]);
        viewModel.companySelected = true;
        viewModel.companyId = companyId;
        viewModel.companySelectList = viewModel.isAllowedMaintain ?
                new SelectList(context.GetCompaniesAll(), "companyId", "name",companyId) :
                new SelectList(context.GetCompaniesByUser(SessionWrapper.UserId.Value), "companyId", "name",companyId);
        viewModel.siteSelectList = new SelectList(context.GetSitesByCompany(companyId,false),"siteId","name") ;
        viewModel.siteSelectList1 = new SelectList(context.GetSitesByCompany(companyId, false), "siteId", "name");
        viewModel.hasSites = context.GetSitesByCompany(companyId, false).Count() > 0;

        if(!Request["site"] == null)
        {
            int? siteId  = stringToNullInt(Request["site"]);
            viewModel.site = context.GetSiteById(siteId).FirstOrDefault();
            viewModel.siteSelectList = new SelectList(context.GetSitesByCompany(companyId, false), "siteId", "name", viewModel.site.siteId.Value);
        }
        if(!Request["site1"] == null){
            int? siteId  = stringToNullInt(Request["site1"]);
            viewModel.site1 = context.GetSiteById(siteId).FirstOrDefault();
            viewModel.siteSelectList1 = new SelectList(context.GetSitesByCompany(companyId, false), "siteId", "name", viewModel.site1.siteId.Value);
        }
     }
}

View

@using (Html.BeginForm())
{
    @Html.ValidationSummary(false, "Please fix these errors.");

<div id="CustomerSelect">
    <div class="labels">
            <b class="head">Select Customer</b>
        </div>
        <div class="editors">
    @Html.DropDownList("company", @Model.companySelectList, "Please Select Customer", new Dictionary<string, object> { { "class", "selectList" }, { "onchange", "submit()" } })
        </div>
</div>
    if (Model.companySelected)
    {
        if (!Model.hasSites)
        {
            <div class="result">
                <p>
                    <b class="head">There are no sites found.</b>
                </p>
            </div>
        }
        else
        {
            <div id="SiteSelect">
                <p class="labels">
                    <b class="head">Select Site</b>
                </p>
                <p class="editors">
                   @Html.DropDownList("site",@Model.siteSelectList,"Please Select Site",new Dictionary<string,object>{{"class","selectList"},{"onchange","submit()"}})
                    @Html.DropDownList("site1",@Model.siteSelectList1,"Please Select Site",new Dictionary<string,object>{{"class","selectList"},{"onchange","submit()"}})
                </p>
            </div>
       }
    }
}

Now, when I select the top one "site", it has the correct selected value (when i debug in the controller) and the correct items attribute is set to true. However every time the page loads, it selects "Please Select Sites" however when i change the second one ("site1") everything seems to work fine.

Any Suggestions? Thanks.

I noticed something else weird that happens, is if I change the code inside:

if(!Request["site"]==null){
}

to use viewModel.site rather than viewModel.site1 it will work... something weird is going on here

Edit: Resolved

The fix was to change everything to a different name. I think somehow, when i call

Html.DropDownList("site",....) 

it tries to match it to the property, site, in my SitesViewModel, which is not what I wanted! I have currently renamed it to "site1" and everything appears to work properly, this explains why in the code above, it didn't work at all, then when I added a site1 property as per the answer by Secret Squirrel,

Html.DropDownList("site1",...) didn't work either!

I hope this helps someone in the future because by god that took ages to work out!

2

There are 2 answers

1
usr On

Try adding ModelState.Clear() just before you return from your action method. THe MVC helpers sometimes take the value from the model state. This test will tell you if ModelState is your problem.

Edit: After you have added this, both lists should behave identically.

2
Squirrel5853 On

do you not just simply need a

ViewModel.site1
ViewModel.site2

??

as is not the final parameter the selected item, so upon debug yes it will have the correct item selected. but then it will drop into the second part and

ViewModel.site

will become something else?