jdstaerk
jdstaerk

Reputation: 892

MVC - Variable in .cshtml file which updates the html when the controller calls it

this is probably a pretty basic thing for you guys, but I still can't figure it out. Let's say I have a View:

myView.cshtml

<div>
    <p>Some content here</p>
    @MyHTMLVariable //Calls updateHTML -> MyHTMLVariable = s
    <p>Some more content over here</p>
</div>

myController.cs

public string updateHTML() 
{
 s = "I'm a string"; //Changes dynamically, handled by different stuff outside
 //Any string to html-conversion needen?
 return s;
}

How can I "update" the variable in the view / how do I have to initialize it?

Cheers,

DDerTyp

Upvotes: 0

Views: 4239

Answers (2)

Olumide
Olumide

Reputation: 368

Use Razor's @functions code block to declare your functions within your view this way...

@functions {
    public string updateHtml() 
    {
        string s = "I'm a string";/*or whatever dynamic stuff you wanna do*/
        return s;
    }
}

@{
    string myHtmlVariable = updateHtml();
}

Then use @myHtmlVariable within your code.

Upvotes: 1

Peter Pompeii
Peter Pompeii

Reputation: 1445

You can use the ViewBag for this. In your template use @ViewBag["MyHTMLVaribale"] and in your controller method use ViewBag["MyHTMLVariable"] = "I'm a string";

Upvotes: 0

Related Questions