提交下拉列表后,出现MVC错误

时间:2018-11-26 19:38:58

标签: c# asp.net-mvc drop-down-menu

我有一个下拉列表,提交后出现错误http://prntscr.com/lnagi8

这是视图

 @Html.DropDownListFor(m => m.SelectedAgrBall, Model.agrBall)
    <input type="submit" value="save" />

这是控制器(发布)

[HttpPost]
public ActionResult Main(string Years, string Periods, Organisations m)
{
    string s = m.SelectedAgrBall;
    int ss = int.Parse(s);
    string t = Years;
    string b = Periods;
    return View();
}

我该怎么办? 控制器

public ActionResult Main()
    {
        aspregistrationEntities1 obj = new aspregistrationEntities1();

        List<agrBal> aggrBad = obj.agrBals.ToList();
        List<agrBReceiv> aggrRec = obj.agrBReceivs.ToList();

        SortedSet<string> org = new SortedSet<string>();
        List<SelectListItem> items = new List<SelectListItem>();
        Dictionary<int, string> orgNames = new Dictionary<int, string>();

        foreach (agrBal tmp in aggrBad)
        {
            org.Add(tmp.ORG.ToString());
        }
        foreach(agrBReceiv tmp in aggrRec)
        {
            orgNames.Add(int.Parse(tmp.PBS.ToString()), tmp.KBO_RU.ToString());
        }

        //Drop organisations in dropdownlist
        var types = new List<SelectListItem>();
        foreach (string tmp in org)
        {
            string s = tmp+" - "+orgNames[int.Parse(tmp)];
            SelectListItem item1 = new SelectListItem() { Text = s, Value = tmp.ToString() };
            items.Add(item1);
        }

        Organisations m = new Organisations() {
             agrBall= items
        };
        return View(m);
    }

模型

{
public class Organisations
{
    public List<SelectListItem> agrBall { get; set; }
    public string SelectedAgrBall { get; set; }
}
}

2 个答案:

答案 0 :(得分:1)

您在HttpPost操作上返回不带模型的View,因此会发生空引用异常,因为您正在Main.cshtml中使用Model对象

您应该将模型对象传递给视图。

(我认为),如果您的模型是Organizations m

[HttpPost]
    public ActionResult Main(string Years, string Periods, Organisations m)
    {
        string s = m.SelectedAgrBall;
        int ss = int.Parse(s);
        string t = Years;
        string b = Periods;
        return View(m);
    } 

答案 1 :(得分:0)

遵循furkanhb,然后修改了model / post方法,以允许使用预选值重新加载页面

public class Organisations
{
    public List<SelectListItem> agrBall { get; set; }
    public SelectListItem SelectedAgrBall { get; set; }
}

[HttpPost]
public ActionResult Main(string Years, string Periods, Organisations m)
{
    string s = m.SelectedAgrBall.Value;
    int ss = int.Parse(s);
    string t = Years;
    string b = Periods;
    return View(m);
}