heyNow
heyNow

Reputation: 886

mvc use variable in layout page instead of its string value

This is probably a n00b question, I'm trying to get a string variable in my MVC _layout page

so far i have

EDIT:

@{
   string myVariable = @Html.Action("GetUserName", "UserController");
}

I need to show the myVariable multiple times on the page. Hence I need to store it somewhere rather than calling the @Url.Action("GetUserName", "UserController"); multiple times.

Is there a way to do this in mvc?

EDIT 2:

I used string myVariable = ViewBag.GetUserName() where

in my BaseController(), I have

public BaseController(){
  ViewBag.GetUserName = new Func<string>(GetUserName);
}

[AllowAnonymous]
public string GetUserName()
{
  return "Mark ZuckerBerg";
}

When i run my project I get, Cannot perform runtime binding on a null reference

Upvotes: 2

Views: 2343

Answers (2)

Arghya C
Arghya C

Reputation: 10068

I think what you want is to call that action in YOUR controller action, and use the result. You can either pass the value as model to the view or pass via ViewBag.

public ActionResult MyAction()
{
    var userName = new UserController().GetUserName();

    return View(userName);
    //OR
    ViewBag.UserName = userName;
    return View();
}

Or, if you want to use in _Layout.cshtml create a child action, in UserController : BaseController

    [ChildActionOnly]
    public ActionResult UserName()
    {
        return new ContentResult { Content = "Mark ZuckerBerg" };
    }

and call in _Layout.cshtml

    @{Html.Action("UserName", "User")}

Upvotes: 2

Nathan
Nathan

Reputation: 1520

Have you tried using razor?

<input type="hidden" value="@myVariable" id='hidden-username'/>

Then access it on javascript/jQuery like this:

var hiddenUserName = $("#hidden-username").val();

Similarly, you can bind it to any other object that accepts the value of it:

<label id='lbl-username'>@myVariable</label>
<input type="text" value="@myVariable" />

Hope this helps.

How you get string myVariable depends upon you, but if you want it without any ajax calls, then you should bind it to the model of the page.

Controller Action:

public ActionResult YourPage()
        {
            YourPageModel pageModel = new YourPageModel();
            pageModel.UserName = GetUserName(userId);
            return View(pageModel);
        }

CSHTML(View):

@model  YourProject.YourPortal.Web.ViewModels.YourPageModel

 <label id='lbl-username'>@Model.UserName</label>

Upvotes: 2

Related Questions