Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC how to return a view with a parameter

At the moment I have a Method that work, it is working when clicking a link here the code in Razor:

@Html.ActionLink("New User ,Register", "Register", new { OpenID = Model.OpenID })

I would like have the same effect with but returning the View from the Controller, at the moment I'm using this code with no success

return View("Register", lm);

I'm pretty new at MVC so I'm a bit confused. The view returned with my last code miss smt and I support is connected with the part new { OpenID = Model.OpenID }

Could you point me out in the right direction?

This how it is the method for my controller:

public ActionResult Register(string OpenID)
like image 414
GibboK Avatar asked Jul 13 '12 18:07

GibboK


People also ask

What does return View () in MVC do?

The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called. For example, the About ActionResult method name of the controller is used to search for a view file named About.

How can call another view with parameter from controller in MVC 4?

Redirection is very easy, you just call controller and then action in that as above suggested. There is option available to pass parameter too. return RedirectToAction("Tests", new { ID = model.ID, projectName = model. ProjectName });

Does the controller return a view?

A controller action might return a view. However, a controller action might perform some other type of action such as redirecting you to another controller action.


2 Answers

Try to avoid ViewData and ViewBag . try to use strongly typed ViewModels. That makes your code clean (and the next developer who is gonna maintain your code, HAPPY)

Have a Property called OpenID in your ViewModel

public class RegisterViewModel
{
     //Other Properties also
     public string OpenID { set; get; }
}

Now you can set this value when returning the view, in your action method:

public ActionResult Register(string OpenId)
{
     var vm = new RegisterViewModel();
     vm.OpenID = OpenId;
     return View(vm);
}
like image 57
Shyju Avatar answered Oct 02 '22 05:10

Shyju


You can add any data you want to a ViewBag variable.

In your controller you'd set the value as such.

Controller

public ActionResult Register()
{
    ViewBag.OpenID = OpenID;

    return View()
}

And in your razor view you can access it the same way

MVC3 Razor View

@ViewBag.OpenID
like image 22
Jerry Avatar answered Oct 02 '22 05:10

Jerry