'How can I pass a String as a model to a View in MVC 5?

I have an action defined like this:

    public ActionResult TempOutput(string model)
    {
        return View(model);
    }

And also, I have its view defined like this:

@model String

@{
    ViewBag.Title = "TempOutput";
}

<h2>TempOutput</h2>

<p>@Model</p>

Then, at one place, I have a return statement like this:

return RedirectToAction("TempOutput", "SEO", new { model = "Tester text" });

And the point is that when I get to my TempOutput view I get an error message saying "The view 'Tester text' or its master was not found or no view engine supports the searched locations.". But I jsut want to print the value of the string inside my view. How can I achieve it?



Solution 1:[1]

You are calling different override of View than you want:

View(string viewName);

You want to call View(string viewName, string masterName, object model) like following:

return View(null, null, model);

You can also specify explicit value (i.e. "TempOutput") for view name.

Alternatively you can force selecting View(object model) override by casting "model" to object:

return View((object)model);

Or, you can overload it using Named Arguments

return View(model: model)

Solution 2:[2]

If I remember correctly if you have to use the RedirectToAction you can pass model data like this:

TempData["model"] = "Tester text";
return RedirectToAction("TempOutput", "SEO");

More information about TempData found here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iemre
Solution 2 Cubicle.Jockey