【问题标题】:Effective ViewBag using in MVC在 MVC 中使用的有效 ViewBag
【发布时间】:2014-11-03 15:13:01
【问题描述】:

我需要为 HttpVerb 使用相同的 ViewBag 对象,它们是 HttpGet 和 HttpPost。因此我不想声明 ViewBags 两次。我创建了一个参数方法,并且每当我想使用它时都会调用这个方法遵循示例。是正确的方法还是您对此问题有任何解决方案?

public ActionResult Index()
{
    SetViewObjects(null);
    return View();
}

[HttpPost]
public ActionResult Index(Person model)
{
    SetViewObjects(model.PersonId);
    return View(model);
}

public void SetViewObjects(short? personId)
{
    IEnumerable<Person> person = null;

    if(personId.HasValue)
    {
        person = db.GetPerson().Where(m=>m.PersonId == personId);
    }
    else
    {
        person = db.GetPerson();
    }

    ViewBag.Person = person;
}

【问题讨论】:

    标签: asp.net asp.net-mvc viewbag httpverbs


    【解决方案1】:

    Viewbag 是动态分配的。你不需要在你的 HttpGet Action 中声明。 您可以在 HttpGet Index 视图中使用 ViewBag.Person 而无需在相应的操作中声明它。 它的值为 null。

    【讨论】:

    • 首先,感谢您的回复。如果我没有在我所谓的页面中声明 ViewBag,则会引发异常。因此我在方法中使用了 viewbag 而不是使用两次。
    【解决方案2】:

    只需使用this.SetViewObjects

    public ActionResult Index()
    {
        this.SetViewObjects(null);
        return View();
    }
    
    [HttpPost]
    public ActionResult Index(Person model)
    {
        this.SetViewObjects(model.PersonId);
        return View(model);
    }
    

    只需将其作为 ControllerBase 的扩展方法即可,例如

    public static void ControllerExt
    {
        public static void SetViewObjects(this ControllerBase controller,short? personId)
        {
         IEnumerable<Person> person = null;
    
        if(personId.HasValue)
        {
            person = db.GetPerson().Where(m=>m.PersonId == personId);
        }
        else
        {
            person = db.GetPerson();
        }
    
          controller.ViewBag.Person = person;
        }
    }
    

    【讨论】:

    • 它看起来很有用。好吧,我想问一个问题?在方法中使用 pluratily viewbag 是真的吗?
    【解决方案3】:

    你说你需要使用相同的 ViewBag 对象到底是什么意思?每次调用 SetViewObjects 函数时,它都会创建一个新的 ViewBag 对象。

    如果您需要使用 ViewBag 来传递数据集合,我建议您使用以下方法(这仍然不是最好的方法):

        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Person = db.GetPerson();
            return View();
        }
    
        [HttpPost]
        public ActionResult Index(User model)
        {
            ViewBag.Person = db.GetPerson().Where(m => m.PersonId == model.PersonId);
            return View(model);
        }
    

    虽然重载的 Index 函数对我来说没有多大意义 - 你从表单 Post 中获取一个 User 模型,然后在数据库中找到一个具有相同 id 的用户 - 这很可能与那个用户是同一个用户您从视图中收到,然后将两个模型类传递给同一个视图,但方式不同。无论如何,理想情况下我会使用以下appr:

        [HttpGet]
        public ActionResult Index()
        {
            return View(db.GetPerson());
        }
    
        [HttpPost]
        public ActionResult Index(User model)
        {
            return View(db.GetPerson().Where(m => m.PersonId == model.PersonId));
        }
    

    【讨论】:

      猜你喜欢
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多