Creating buttons dynamically in MVC 5

2019-08-29 05:44发布

问题:

I need to read data from database and create buttons as much as rowcount on a view dynamically on the pageload.

Also the button text is going to be taken from database too.

i.e; 3 rows in datatable, 3 buttons with their texts from fields in same datatable.

I couldn't manage to find an example to create buttons on page load. Most of the "dynamic buttons" examples I came across are triggered by a button click.

I suppose I'm going to read the data in a [HttpGet] in the controller.There I can get the necessary row count and data, but I have no idea about creating the buttons from that point.

回答1:

You should be able to achieve what you want by using razor.

See this example: Razor C# loops

Just provide a list in the model, and you can iterate over this.


Edit for clarification:

You could do something like this:

<ul>
    @foreach (var x in Model.YourList)
    {
        <li>
            <button type="button">@x.ButtonName</button>
        </li>
    }
</ul>

You can then populate the list however you want in your controller. Once it is returned with the view, the list of buttons will be rendered as you seek.