0

I am having issue on passing string parameter from controller to view in the controller I have:

namespace Map02.Controllers
{
    public class AppController : Controller
    {

        public ActionResult Index(string name)
        {
            string str = name;
            return View(str);
        }

    }
}

and in view I have:

@model string
@{
    ViewBag.Title = "";
}

<h2>AppContent</h2>

<p>@str</p>

but I am getting this error:

enter image description here

8
  • 4
    Change @str to @Model Commented Sep 23, 2016 at 5:59
  • 1
    You also need to use return View((object)str); otherwise it will try to find a view that matches str Commented Sep 23, 2016 at 6:00
  • Hi Frahad, thanks for reply I am not getting any error now but I am not still getting the output either. Commented Sep 23, 2016 at 6:09
  • @StephenMuecke, I update the return View((object)str); but not getting any output in page! Commented Sep 23, 2016 at 6:11
  • Then it means the value of name is null Commented Sep 23, 2016 at 6:11

1 Answer 1

4

To pass a string to the view as the Model, you can do:

public ActionResult Index()
{
    string str = name;;
    return View((object)str);
}

You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:

return View("Index", str);

Then in your view, just type it as a string:

 @model string
@{
    ViewBag.Title = "";
}

<h2>AppContent</h2>

<p>@Model</p>
Sign up to request clarification or add additional context in comments.

4 Comments

Important : You have to change <p>@str</p> to <p>@Model</p>
return View("Index", str); does not work! (its calling this overload
I think this will work return View("Index",(object)str);
Yes it will, but that's identical to return View((object)str); so its a bit pointless :)

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.