0

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

10
  • how are you calling updateHTML? through ajax.. Commented Aug 8, 2016 at 18:23
  • Yep, exactly. But how do I place/initialize the Variable in myView.cshtml? Maybe that was unclear, sorry. - To make it even more clear, can someone give me the sourcecode for the myView.cshtml file? What do I have to write betweenthe <p>-tags? Commented Aug 8, 2016 at 18:26
  • 1
    No you cannot do that. Server side variables are render as their values in view.. Commented Aug 8, 2016 at 18:28
  • You can intiallize @{ var MyHTMLVar = "" } in this way Commented Aug 8, 2016 at 18:29
  • Okay, thank you @mmushtaq =) If it is not possible the way I want, could I store the source code of myView in a string, insert the MyHTMLVariable at the specific location (in the string) and write the "new" source code in the myView.cshtml? Commented Aug 8, 2016 at 18:33

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.