1

I want to reuse my razor pages instead of having multiple similar views in mvc, I don't want to use a partial view. Thus I want to pass a parameter from a controller to razor page.

In the razor page my input will be something like below

public async Task OnGet(int? x,int?y)

How can i call this function/razor page from my mvc controller?

Gino
  • 39
  • 1
  • 8

3 Answers3

3

Controller

public class HomeController : Controller
 {
        // GET: /<controller>/
        public IActionResult Index()
        {           
            return RedirectToPage("/index", new { name = "Arun Kumar"});
        }
 }

Razor Page:

public class IndexModel : PageModel
 {
        public string FullName { get; set; }

        public void OnGet(string name)
        {
            FullName = name;
            ViewData["heading"] = "Welcome  to ASP.NET Core Razor Pages !!";

        }
 }

Razor Page View:

@page
@model RazorMVCMix.Pages.IndexModel



<h1>@ViewData["heading"]</h1>

<h2>@Model.FullName</h2>

Output here:

output

Always_a_learner
  • 1,254
  • 1
  • 8
  • 16
0

Controllers are just classes you can call action like methods from another controller.

https://softwareengineering.stackexchange.com/questions/264392/is-a-good-practice-to-call-a-controller-function-from-another-controller

How to call another controller Action From a controller in Mvc

https://forums.asp.net/t/1645726.aspx?how+to+call+a+controller+action+from+another+controller

Ajay Kelkar
  • 4,591
  • 4
  • 30
  • 29
  • How do i return a razor page with parameters from an mvc controller? What is the syntax – Gino May 27 '20 at 06:10
  • The razor page you want to return must be from some controller action . Call that action using new Controller.Action(params) return result as result is IActionResult for mvc. You dont need to cal View() method just return result. – Ajay Kelkar May 27 '20 at 06:12
  • Razor pages don’t have a controller – Gino May 27 '20 at 06:14
  • If you dont want partial view return that razor from another controller action call that action from your controller there you can pass down view model as param. Or use custom HtmlHelper instead of razor view. – Ajay Kelkar May 27 '20 at 06:19
  • Appreciate your effort but doesn’t answer my question of returning/calling razor page method with param from mvc controller output – Gino May 27 '20 at 06:25
0

In your controller action, use RedirectToPageResult:

return new RedirectToPageResult("/YourRazorPage", new {x = 1, y = 2});
Mike Brind
  • 28,238
  • 6
  • 56
  • 88
  • 1
    thanks the only problem is my controller which is located in "~/Areas/Base/Controllers/HomeController.cs" and my razor pages are in "~/Pages/Objects/". When using "return RedirectToPageResult("/YourRazorPage".... it isattempting look within "~/Areas/Base". The only method which doesn't use relative referencing is "Redirect("/Obejcts") but i cannot pass parameters with this method. – Gino May 27 '20 at 13:30