简体   繁体   English

为什么我们还需要在HttpPost Action中传递SelectList的ViewBag呢?

[英]Why do we need to pass the ViewBag of SelectList in HttpPost Action too?

I have select-list items that are stored in a ViewBag. 我有一个存储在ViewBag中的选择列表项。 I don't understand why we should declare this ViewBag in both, HttpGet and HttpPost actions? 我不明白为什么我们应该在HttpGet和HttpPost操作中声明这个ViewBag?

If we don't declare it again in HttpPost action, the validation will not work and we will get exception. 如果我们不在HttpPost操作中再次声明它,则验证将不起作用,我们将获得异常。 But how does this happen technically? 但这在技术上是如何发生的?


Actions: 操作:

@Html.DropDownListFor(m => m.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories, "Select Category", new { @class = "form-control" })

List: 列表:

 @Html.DropDownListFor(m => m.CategoryId, (IEnumerable<SelectListItem>)ViewBag.Categories, "Select Category", new { @class = "form-control" }) 

The raised exception when I delete the ViewBag from HttpPost Action. 从HttpPost Action中删除ViewBag时引发的异常。 I wonder why that 我想知道为什么
key = CategoryId? key = CategoryId? how does this key work? 这个关键是如何工作的?

Screenshot : 截图:

截图

You may be overthinking it. 你可能会过度思考它。 Consider it simply... 简单地考虑一下......

Both actions return the same view: 这两个操作都返回相同的视图:

public ActionResult New()
{
    //...
    return View();
}

And that view uses a value from the ViewBag : 该视图使用ViewBag的值:

(IEnumerable<SelectListItem>)ViewBag.Categories

In order for the view to use that value, that value has to be in the ViewBag . 为了使视图使用该值,该值必须位于ViewBag So any action which returns that view will need to populate that value. 因此,返回该视图的任何操作都需要填充该值。 Which is why there's an error when you don't populate that value. 这就是为什么在不填充该值时会出现错误的原因。 The error is telling you that you're trying to use a ViewBag value that doesn't exist. 该错误告诉您正在尝试使用不存在的ViewBag值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM