2

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

13
  • What url are you actually trying to generate? Do you want "User/GetUserName/someUserName? (And its "User", not "UserController"). In any case, why assign it to a c# variable first? - it can just be var testName = '@Url.Action(...)'; Commented Aug 24, 2015 at 3:01
  • im not trying to get the string value, i need the result of calling the URL. var testName='Mark Zuckerberg' Commented Aug 24, 2015 at 3:16
  • Then you need to call the controller method. Url.Action() is a method for generating a url (it does not actually call it). But why is the value of your UserName not available in the view? You need to provide some more context to understand what you really want to do. Commented Aug 24, 2015 at 3:18
  • all the controllers get called using javascript ajax calls, i just need to call it here using MVC as I want the value loaded before any of the javascript loads. Commented Aug 24, 2015 at 3:40
  • 1
    Then you need to make an ajax call to that controller method to get the value it returns. Commented Aug 24, 2015 at 3:53

2 Answers 2

2

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")}
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this but UserController is null at that point, i think the _layout gets initialized first
Did you try this inside the controller action method or directly inside _Layout.cshtml file? I'm suggesting to do this inside your controller action and then passing on the value to the view.
doing ViewBag.UserName = userName; and refrencing @ViewBag.UserName in the layout page produces a blank result
Yes, Layout is called before before the action result. Have edited the answer with an alternative approach.
it works! finally! I tried you edited answer. Can't believe something so simple is made into so complicated in MVC
2

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>

4 Comments

could you tell me how @myVariable would get its value (controller or any other way) ?
I would suggest binding the page to a model, and from here you can bind call the model to use the variable. I can show you an example if you want to.
is there a way other than model?
I think there are some ways but it's much messier, like loading everything via ajax call and appending it to the multiple times your username on load. The best way you could do this is via binding your view to the viewmodel. In case you need some walk through on using model binding, I've added a simple example you could start on.

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.