使用下拉列表回发绑定radiobuttonlist

时间:2012-04-01 15:49:48

标签: asp.net-mvc asp.net-mvc-3

我将使用dropdownlist postback绑定radiobuttonlist。为此我将两个操作置于控件中,但是当视图加载错误时:object refrence null 事实上,在回发下拉列表之前想要绑定radiobutton,这个时间对象是null 请告诉我

    namespace Charge.Models
    {
    public class SellChargeModel
    {
    public int Id { get; set; }

    public string Serial { get; set; }

    public DateTime Date { get; set; }

    public string Bank { get; set; }

    public IEnumerable<SelectListItem> Companys { get; set; }

    public IEnumerable<SelectListItem> types { get; set; }

    public ChargeCompanyModel ChargeCompany { get; set; }

    public ChargeTypeModel ChargeType { get; set; }
    }
    }


     namespace Charge.Controllers
     {
     public class ChargeController : Controller
    {
    [HttpGet]
    public ActionResult Main()
    {
        var chargeEntities = new ChargeEntities();
        var sell = new SellChargeModel();
        var query = chargeEntities.ChargeCompanies.ToList();
        var listCompany =
            query.Select(
                company => new SelectListItem {Text = company.Name, Value =                         company.Id.ToString()})
                .ToList();
        sell.Companys = listCompany;
        return View(sell);
    }

    [HttpPost]
    public ActionResult Main(FormCollection form)
    {
        var id = Convert.ToInt32(form["Companys"]);
        var chargeEntities = new ChargeEntities();
        var query = chargeEntities.ChargeTypes.Where(x => x.CompanyId == id).ToList();
        var chargeType = new SellChargeModel();
        var selectList = query.Select(x => new SelectListItem {Text = x.Type, Value = x.Id.ToString()}).ToList();
        chargeType.types = selectList;
        return View(chargeType);
    }

     }
     }

  @model SellChargeModel
  @using Charge.Models
 @{
ViewBag.Title = "Main";
}

  <h2>Main</h2>
   @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "dForm" }))
  {
  <div>
    @Html.DropDownListFor(x => x.Companys, Model.Companys, new {onchange =             "$('#dForm').submit()"})
</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<div>
    @foreach (var c in Model.types)
    {
        @Html.RadioButtonFor(x => x.ChargeType, c.Text, c.Value)
        @Html.Label(c.Text)
    }
  </div>

   }

2 个答案:

答案 0 :(得分:1)

[HttpPost]操作中,您需要设置chargeType.Companys属性的方式与[HttpGet]操作相同(使用chargeEntities.ChargeCompanies,然后将其映射到{ {1}})。您需要这样做的原因是因为您重新显示了根据此属性显示下拉列表的同一视图。如果属性为null,那么当您尝试显示DropDownList时,视图中会出现NRE。

答案 1 :(得分:1)

ASP.NET MCV没有ViewState。因此,它不会将您的数据保留在回发中以用于下拉列表。这是ASP.NET MVC的行为。您收到null错误的原因是在post post方法中返回一个Companys属性为null的对象。您可能希望在返回之前重新加载该属性中的数据,就像您在HttpGet操作方法中所做的那样