简体   繁体   中英

How to pass List String to TempData Asp.Net

I have a Tempada to show a list of error in a msg error,i create a List and in my foreach, each error find it, i add a error in my List and later i show this list in TempData

public IActionResult Demo()
{
    List<string> LogErros = new List<string>();
    try
    {      
        foreach (var item in somethings)
        {
            // if have some error add to list   
            LogErros.add();
        }
        if (LogErros.Count > 0)
        {
            TempData["error-message"] = LogErros;
        }
    }
    return View();
}

I try this:

@if (TempData["error-message"] != null)
{
    <div class="alert alert-danger alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
        @TempData["error-message"]
    </div>
}

but get error enter image description here

TempData["error-message"] stores a list of strings as an Object . So you need to get that first, cast it to a list of strings, loop through each one of them and render it.

Razor basically calls the ToString on the expression (in your case, object ) and hence you are seeing your current results

This should work

@if (TempData["error-message"] != null)
{
    var errors = TempData["error-message"] as List<string>;
    <div class="alert alert-danger alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" >x</button>
        @foreach(var errorMessage in errors)
        {
            <p>@errorMessage</p>
        }
    </div>
}

While this works, I recommend not putting a lot of C# code in the view. If it is an asp.net core project, I would recommend creating a tag helper for this. Here is a very simple one.

[HtmlTargetElement("div", Attributes = "messages")]
public class AlertMessagesTagHelper : TagHelper
{
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        StringBuilder str = new StringBuilder();

        var messages = ViewContext.TempData["error-message"] as List<string>;
        if (messages != null && messages.Any())
        {
            str.Append("<div class='alert alert-danger alert-dismissable'>");
            foreach (var message in messages)
            {
                str.AppendFormat("<div>{0}</div>", message);

            }
            str.Append("</div>");
        }
        output.Content.AppendHtml(str.ToString());
    }
}

Now in your _ViewImports.cshtml file, use the addTagHelper method to include all the tag helpers from your project

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, YourAssemblyName

Now in your view or layout, you can call this tag helper by using a div element with the messages attribute

<div messages></div>

Feel free to update the tag helper code to render the HTML markup you want for the messages.

For Non-Asp.Net core projects, you can create an html helper method which does the same thing.

The problem is you are displaying @TempData["error-message"] in your view, but TempData is essentially a Dictionary<string, object> which means when you access the value at that key, the value is an object .

Even if you cast to its actual value ( List<string> ) it will implicitly call .ToString() , which wont automatically display the contents of the list if you just use the @ symbol to render on the page.

First thing you need to do is cast your object to a List<string> :

var errorMessageList = TempData["error-message"] as List<string>;

Then you can iterate over the values in the list:

var errorMessageList = TempData["error-message"] as List<string>;
@if (errorMessageList != null)
{
    <div class="alert alert-danger alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>
        @foreach(var message in errorMessageList)
        {
            @message
        }
    </div>
}

Of course you will have to format this how you want, maybe it should be comma separated? Maybe it should be in their own <span> ... That is up to you.

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