无法获取Controller构建模型表单查询和传入的参数 - 多个模型来获取数据

时间:2014-02-17 23:05:40

标签: c# asp.net-mvc-4 razor

我在这里使用的较大模型中有4个更简单的模型,并使用结果集进行复杂查询。效果很好。我有一个参数传入以完成包含所有部分的新表中的更新。

因此,int(传递参数)按照预期从上一个视图的操作进入 从控制器中的查询预期的数据查询..

我用单一模型构建了其他操作,没有问题。

我尝试创建一个新模型,然后专门添加到模型中,我在int上得到一个null参考错误到模型值:(对象空引用错误) 代码当前不存在:

var model = new AddCompToEventClass();
model.Compeditor.CompeditorId = compeditorid;

我无法弄清楚如何将所有内容都放入模型中以传递给下一个视图。

控制器代码:有compeditorId评论。 compeditorid参数按预期传递给控制器​​。

    public ActionResult AddCompToEventClass (int compeditorid)
{
    // ?? model.Compeditor.CompeditorId = compeditorid;
    var model = from o in _db.Events
                join o2 in _db.Event_Classes on o.EventID equals o2.EventID
                where o.EventID.Equals(o2.EventID)
                join o3 in _db.Class_Definitions on o2.ClassID equals o3.Class_Definition_ID
                where o2.ClassID.Equals(o3.Class_Definition_ID)
                where o.CurrentEvent.Equals(true)
                select new AddCompToEventClass { Event = o, Event_Class = o2, Class_Definition = o3 };

return View(model);

这是模型(基于4个其他模型)

 namespace eManager.Web2.Models
{
    public class AddCompToEventClass
    {
        public Compeditor Compeditor { get; set; }
        public Event Event { get; set; }
        public Event_Class Event_Class { get; set; }
        public Class_Definition Class_Definition { get; set; }
    }
}

更新的代码:我现在获得了竞争对手和查询,但只有查询被传递到模型中...在查询中有竞争对手我得到了一个Linq异常。

public ActionResult AddCompToEventClass (int compeditorid)
    {
        var Compeditor = new Compeditor();
        Compeditor.CompeditorId = compeditorid;

        var model = from o in _db.Events
                    join o2 in _db.Event_Classes on o.EventID equals o2.EventID
                    where o.EventID.Equals(o2.EventID)
                    join o3 in _db.Class_Definitions on o2.ClassID equals o3.Class_Definition_ID
                    where o2.ClassID.Equals(o3.Class_Definition_ID)
                    where o.CurrentEvent.Equals(true)
                    select new AddCompToEventClass { Event = o, Event_Class = o2, Class_Definition = o3 };



    return View(model);
    }

1 个答案:

答案 0 :(得分:0)

  

我在模型值的int上得到一个null引用错误:(对象空引用错误)

你可能缺少另一个构造函数:

var model = new AddCompToEventClass();

// model.Compeditor is most likely null

model.Compeditor = new Compeditor();

model.Compeditor.CompeditorId = compeditorid;

<强>更新

更新了查询:

public ActionResult AddCompToEventClass (int compeditorid)
{
  var model = from o in _db.Events
    join o2 in _db.Event_Classes on o.EventID equals o2.EventID
    where o.EventID.Equals(o2.EventID)
    join o3 in _db.Class_Definitions on o2.ClassID equals o3.Class_Definition_ID
    where o2.ClassID.Equals(o3.Class_Definition_ID)
    where o.CurrentEvent.Equals(true)
    select new AddCompToEventClass 
    {
      Event = o, 
      Event_Class = o2, 
      Class_Definition = o3,
    };

  model.Compeditor = new Compeditor
  {
    CompeditorId = compeditorid
  };

  return view(model);
}