Bhargav
Bhargav

Reputation: 451

How to format display text in mvc page using razor DisplayFor?

I am working on asp.net mvc3 application.

In this user can post data, i am using textarea for input. This data is stored into database and i am retrieving it using razor @Html.DisplayFor().

My Data for textarea is like this (inputed by user)

Oh woooah, oh woooooah, oh wooooah, oh.
You know you love me, I know you care,
you shout whenever and I’ll be there.
You are my love, you are my heart
and we will never ever ever be apart.
Are we an item? girl quit playing,
we’re just friends, what are you saying.
Said there’s another, look right in my eyes,
my first love broke my heart for the first time.
And I was like…


Baby, baby, baby oooooh,
like baby, baby, baby noooooooo,
like baby, baby, baby, ooooh.
Thought you’d always be mine, mine (repeat)

and when i retrieve it using this,

<em>@Html.DisplayFor(model => item.inputvalue)</em>

but it is displayed as unformated text like below,

Oh woooah, oh woooooah, oh wooooah, oh. You know you love me, I know you care, you shout whenever and I’ll be there. You are my love, you are my heart and we will never ever ever be apart. Are we an item? girl quit playing, we’re just friends, what are you saying. Said there’s another, look right in my eyes, my first love broke my heart for the first time. And I was like… Baby, baby, baby oooooh, like baby, baby, baby noooooooo, like baby, baby, baby, ooooh. Thought you’d always be mine, mine (repeat)

How can i format display text? Is there any property to display this as formated text?

Upvotes: 1

Views: 6529

Answers (2)

Bhargav
Bhargav

Reputation: 451

I made few changes in Darin Dimitrov's answer. Its now working perfect..

Thanks Darin Dimitrov for your help.

public static class HtmlExtensions

    {
        public static IHtmlString DisplayFormattedData(this HtmlHelper htmlHelper, string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return MvcHtmlString.Empty;
            }

            string myString=data;
                myString = myString.Replace("\n", "<br>");

                return new HtmlString(myString);
        }
    }

Upvotes: -1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

You should replace new lines with <br/>. You could write a custom helper to do this:

public static class HtmlExtensions
{
    public static IHtmlString DisplayFormattedData(this HtmlHelper htmlHelper, string data)
    {
        if (string.IsNullOrEmpty(data))
        {
            return MvcHtmlString.Empty;
        }

        var result = string.Join(
            "<br/>", 
            data
                .Split(new[] { Environment.NewLine }, StringSplitOptions.None)
                .Select(htmlHelper.Encode)
        );
        return new HtmlString(result);
    }
}

and then:

@Html.DisplayFormattedData(item.inputvalue)

Upvotes: 7

Related Questions