简体   繁体   English

SelectList选定值问题

[英]SelectList Selected Value Issue

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. 现在,当我选择最上面的一个“站点”时 ,它具有正确的选定值(当我在控制器中调试时),并且正确的items属性设置为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. 但是,每次页面加载时,它都会选择“请选择站点”,但是当我更改第二个站点 (“ site1”)时,一切似乎都正常。

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 使用viewModel.site而不是viewModel.site1它将起作用...这里发生了一些奇怪的事情

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! 它尝试将其与我的SitesViewModel中的属性site匹配,这不是我想要的! 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, 我目前已将其重命名为“ site1”,并且一切似乎都能正常工作,这解释了为什么在上面的代码中它根本无法工作,然后当我根据Secret Squirrel的回答添加了site1属性时,

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

I hope this helps someone in the future because by god that took ages to work out! 我希望这对以后的人有所帮助,因为神花了很长时间才能锻炼!

Try adding ModelState.Clear() just before you return from your action method. 从动作方法返回之前,请尝试添加ModelState.Clear()。 THe MVC helpers sometimes take the value from the model state. MVC助手有时会从模型状态中获取价值。 This test will tell you if ModelState is your problem. 该测试将告诉您ModelState是否是您的问题。

Edit: After you have added this, both lists should behave identically. 编辑:添加此后,两个列表的行为应相同。

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? 会变成其他东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM