简体   繁体   中英

How to get the ViewBag from the view? always returns null

在控制器中,我执行一个ViewBag,然后将其传输到视图,然后在其中填充数据并希望在发布请求中发送该数据,但是viewbag返回null,如何从ViewBag返回所选数据

Sorry, but AFAIK this is not how the ViewBag variable was meant to be used. It is for sharing small amounts of data from the Controller to the view (on the client), not the other way around.

To get data back to the server you'll need to explicitly post back the data you need in a request to your server from your client view.

Lets break this down

 @foreach (var item in ViewBag.List)
                        {
                            <option value="@item.Id">@item.Name</option>
                        }

In the above code, ViewBag should exist as a dynamic variable, and if you set List in the view bag object when the view is being requested by the client it will contain whatever data you put there.

<button class="btn" type="submit" name="action">
                        Submit
                    </button>

Here, in the html above, you are now trying to Post back whatever options you select. it is here youll need to specify an endpoint that will recieve the form data and do whatever is required with it

I would take bigger amount of data from MODEL

MODEL

 public string Name{ get; set; }

VIEW

@model IEnumerable<*YourProjectName*.Models.*ModelName*>

Code above, between * * change it to right project name and Model name. It should do it automatically after you write @model

 @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
            </tr>
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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