简体   繁体   中英

How to add 'n' literal control to a view in asp.net MVC5 dynamically?

I am new to MVC and have a basic understanding of it.

I have to add a literal control in view.cshtml dynamically for n times through code(using c#). In aspx.cs we can perform like this,

        string[] url= SingleSignOnManager.SignOut();
        foreach (var obj in url)
        {
          this.LogoutPanel.Controls.Add(new LiteralControl(String.Format("<p><a href='{0}'></a>&nbsp;<img width='1px' src='{0}?wa=wsignoutcleanup1.0' " + "title='Signout request: {0}?wa=wsignoutcleanup1.0'/></p>", obj)));                                                                    
        }

I doubt whether literal is available in MVC or not.How to do this same in a mvc view and controller?

EDIT: I created a model class Url, added code in controller and view.

Model - Url.cs

public class Url
{
    public string[] signedInUrls { get; set; }
}

Controller - ReedController.cs

.
.
.
url = new Url()
{
     signedInUrls = SingleSignOnManager.SignOut()
};

View : sample.cshtml

<html>
<head></head>
<body>
        <div id="main">      
            <div id="Panel">   

                 @model AppOne.Models.Url  

                foreach (string url in Models.Url)
                {
                  <p><a href='@url'></a>&nbsp;<img width='1px' src='@url?wa=wsignoutcleanup1.0' "+" title='Signout request: @url?wa=wsignoutcleanup1.0' /></p>
                }

            </div>

        </div>
</body>

In View, inside foreach loop, i am getting error:

The name 'url' doesnot exist in the current context.

As Stephen suggested, you should Add a List<string> property to your model and use it in view:

@foreach(string s in Model.YourList){
    <p>
    Your text here...use the string like: @s whenever required
    </p>
}

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