1

我需要为 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;
}
4

3 回答 3

2

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

于 2014-09-10T05:31:29.627 回答
1

只需使用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;
    }
}
于 2014-09-10T05:53:07.093 回答
0

你说你需要使用相同的 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));
    }
于 2014-09-10T12:56:13.027 回答