传递回View时,SelectListItem中的InvalidOperationException

时间:2018-06-07 18:47:59

标签: c# asp.net-mvc

我有一个完美运行的SelectList,除非模型再次传递回View(例如当模型无效时)。当它被传回时我得到以下错误。我错过了什么?

抛出InvalidOperationException的行:

  

@ Html.DropDownListFor(m => m.companyId,Model.CompanyList," SELECT COMPANY")

我试过了:

如果g.companyId = null;注释掉了:

  

InvalidOperationException:具有键' companyId'的ViewData项。属于' System.String'但必须属于' IEnumerable'。

如果g.companyId = null;没有注释掉:

  

InvalidOperationException:没有类型为' IEnumerable'的ViewData项。有关键' companyId'。

控制器

[HttpPost]
public ActionResult GCLandingAddUser(GUser g)
{
    //will not accept if phone is same as email and sanitize text inputs

    if (!g.isValid()) {
        g.companyId = null; 
        return View("AddGCLUser", g);
    }
}
public ActionResult GCLandingAddUser()
{
  GUser g=new GUser();
  g.companyList=GetSelectList();
  return View("AddGCLUser",g);
}

模型

public class GUser
{
[Required(ErrorMessage = "company is required")]
[Display(Name = "company id")]
public string companyId { get; set; }

public List<SelectListItem> GetSelectList(){
  var GroupList = new List<SelectListItem>();
  GroupList.Add(new SelectListItem{Text="1",Value="1"});
  GroupList.Add(new SelectListItem{Text="2",Value="2"});
  return GroupList;
}

public bool isValid(){return false;}//guarantees it will be passed back
}

查看(GCLandingAddUser.cshtml)

@model GUser
@using (@Html.BeginForm())
{
<div class="panel-body" id="MyDiv">
    <div>
        @Html.LabelFor(m => m.companyId)
        @Html.DropDownListFor(m => m.companyId, Model.CompanyList, "SELECT COMPANY")
        @Html.ValidationMessageFor(m => m.companyId)
    </div>
</div>  
<input type="submit" value="Submit" />
}  

1 个答案:

答案 0 :(得分:0)

如果要将相同的View返回给用户,则需要再次使用数据填充DropDownList。

[HttpPost]
public ActionResult GCLandingAddUser(GUser g)
{    
    if (ModelState.IsValid) 
    {
        // So something      
        return RedirectToAction("Index");
    }
    g.CompanyList = GetSelectList(); // <------
    return View("AddGCLUser", g);
}