Render a View inside a View in Asp.Net mvc - c#

How do I render a full fledged view (not partial view) inside another view?
Scenario, I have different controller and want the exactly same view to render which is already there under other controller with different layout.
I have Wishlist page in Home Controller which shows list of added products, and when user logged in , when I click on wish list it also show me navigation when user is signed in.
How would I do that??

Not many developers know about this but you can use RenderPage, it's specifically designed for that purpose(to render an MVC view inside another view)
#RenderPage("~/Views/Shared/SampleView.cshtml")

You can still create or use a partial view with its own controller and use the RenderAction()
[ChildActionOnly]
public ActionResult ActionPartialView(string p1)
{
//code...
return PartialView();
}
The above code can be in any controller, its own controller, just call it in razor with that controller.
Razor:
#{ Html.RenderAction("Index", "Home"); }
Hope that helps

Related

How can I show another view in a view

I have 2 action methods(a and b) and 2 views(a and b).
These action methods are having different models. Now I want to show view-b in view-a along with view-a. I don't want to use viewModel.
please help me!!
Put this in View A:
#Html.Action("ActionBName", "ActionBControllerName", new { area = string.Empty })
And in Controller for ViewB:
[ChildActionOnly]
public ActionResult ActionBName()
{
// Generate ViewModel vm
return PartialView("_NameOfViewB", vm);
}
Html.Action will run the Action method from the page to generate the html and the [ChildActionOnly] attribute means it cannot be accessed directly, but only from a View. The View name given in the Action return PartialView("_NameOfViewB", vm); assumes it is located in the Controllers main View folder and has a ViewModel generated with a name vm.
I used an ajax call in document.ready in view A and binded that data in a div.
This solved my problem.

What are the advantages of separate controller per partial view in mvc 4?

I am new to MVC and just have learned about partial views.
What are the differences/advantages between separate controller per partial view vs only one controller per view (containing multiple partial views)?
Some definitions
PartialView are pieces of code you use to add into a View or a result from an Action.
View is a page you want to show to a user and it is returned by an Action from a Controller.
All .cshtml are consider by asp.net mvc as a View, depending on the way you treat the object, it becomes partially or not. (Html.RenderPartial, PartialView controller method, etc..).
What you can do?
Sometimes you need to return just a piece and you can do it by a async request (using ajax). In these cases, you use an action that returns a Partial View.
Sometimes you need to implement an View that need to add a piece of code, so, you can render it using a Partial View.
You can have an View inside the View/Shared folder and this view could use an Partial View. The Partial View could be into the specific folder of the View. For sample:
Views
Product
Item.cshtml // Partial view
Shared
Index.cshtml // View
The content on the Index.cshtml file is:
<div>
#Html.Partial("Item")
</div>
and you have an controller like this:
public class ProductController : Controller
{
public ActionResult Index()
{
return View();
}
}
It will find an View in Product and not found, after will find in the Shared folder and render. The view in shared folder uses the Partial View, so, the context of the execution is in Product and it will render the Item.cshtml partial view from Product Folder.
If you do in your controller this:
public class ProductController : Controller
{
public ActionResult Index()
{
return PartialView();
}
}
It will return just the process of Index.cshtml without any layout page, because you treat it as a Partial View.
Its some advantages you can use of Partial Views.

MVC calling a controller from another section and passing the model in

I have a page that has a search function in a controller which works well
[HttpPost]
public virtual ActionResult Search(SearchModel model)
{
...adds to IEnumerable and such
return View(model);
}
My problem is I have another page with a search box, which I need to redirect to the same view as above. (parameters in the URL is not an option)
#using (Html.BeginForm("Search", "Home", FormMethod.Post, null))
{
#Html.TextBoxFor(t => t.SearchModel)
<input.....
}
but it's not loading up the right URL, it's just adding it to the current one. so instead of example.com/Home/Search it's adding it to the end of where that form is currently located. So if the page was in example.com/About/SearchPage its adding the t.SearchModel to the About/Searchpage
Edit: I have two different Controllers and Views, ControllerA and ViewA works fine, it brings back the search results. I want ViewB, which has an input box, to call ViewA and use ControllerA search technique
You have a nested form. This is not valid HTML. HTML does not allow you to put one form inside another form. You can have more than one form on a page, but you cannot nest them.
I'm also not sure what you mean by "another section", do you mean the #section keyword in Razor? Or do you mean an MVC area? Or something else?

MVC3 Partial view inside Master Page

On my site, I want to display a Login box on all pages. So I wanted to make a partial view page, which I use on my _Layout.cshtml file in Shared.
But where would the controller for this partial view go? And how would my Login button have access to it?
So, when the Request.IsAuthenticated is true, the login box shows 'Logged in as ...', but when the result is false, I get a little table with the usual Username/Password form.
Edit: After trying some answers below, I seem to be stuck in an endless lopp on the GET method below. It it because my partial view is trying to load me _Layout.cshtml file, as it want to accosiate the 'masterpage' with the partial view? And because my partial view is being rendered in _Layout.cshtml, it's lopping?
public class LoginController : Controller
{
//
// GET: /Login/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(LoginModel loginModel)
{
if(ModelState.IsValid)
{
var g = new GallaryImage();
var user = g.LoginUser(loginModel.Username, loginModel.Password);
if(user != null)
{
FormsAuthentication.SetAuthCookie(user.username, false);
return RedirectToAction("index", "Home");
}
ModelState.AddModelError("", "Invalid Username/Password");
}
return View();
}
In my _Layout.cshtml, I am trying to load the partial view like this:
<div style="text-align: right">
#Html.Action("Index", "Login")
</div>
See the issue?
FYI, Views don't have controllers. Controllers have Views. The distinction may seem subtle, but it's not. A view can be used by any number of controllers, and views don't care or know about the controllers. So you have to think about the current URL, which means the current Action Method.
In the case of your login partial, it doesn't need much if anything from the Controller. It's directly accessing the User property of the page to find out if it's authenticated. Your login button is just a form with it's action method set to your login method of your account controller.
Even the username can be displayed from the User property of the page.
Just look at the default MVC app that is generated when you create a new Internet project. It has all this functionality already implemented. Just copy it.
You can give controller name as attribute to Html.Action method
Html.Action("ActionName", "ControllerName")
If you use Razor syntax, you must write #Html.Action("ActionName", "ControllerName") in your view and your Action with name ActionName should return PartialView(which wil be your login area).
Try to use HTML.RenderAction("Action", "Controller") and make sure you are not calling your master page from within the partial view. This has the potential to produce a loop.
I'm using MVC 3 ASPX view engine not razor though.

Re-using a partial view (ascx) across different Controllers and Views

Let's assume I have 2 Controllers, TopicsController and PostsController.
For each controller, I have a couple of views (Index & Details).
The Topic (Index) view inherits System.Web.Mvc.ViewPage<IEnumerable<MessageBoard.Models.Topic>>
The Topic (Details) view inherits System.Web.Mvc.ViewPage<MessageBoard.Models.TopicFormViewModel>
I'm using a TopicFormViewModel because I'm sending additional data along with the Model.
The Post (Details) view just inherits System.Web.Mvc.ViewPage<MessageBoard.Models.Post>
Now, I've created a partial view (CreatePost.ascx) which is (obviously :p) used to create a new Post. I want to be able to re-use this control on all of the views you see above.
Update
I've tried rendering the partial view using <% Html.RenderPartial("New"); %> from my Topics/Index.aspx View, but that results in an exception
The model item passed into the dictionary is of type 'System.Data.Linq.Table`1[MessageBoard.Models.Topic]', but this dictionary requires a model item of type 'MessageBoard.Models.Post'.
Now the problem is that my partial view (CreatePost.ascx) accepts a System.Web.Mvc.ViewUserControl<MessageBoard.Models.Post> and I'm not sure how to pass that from all my views above.
I'm also unsure know how to submit the .ascx values to a certain URL (i.e. /Topics/1/CreatePost), how do I tell the submit button to post to that URL?
Thanks in advance,
Marko
Ciao Marko,
Now the problem is that my partial
view (CreatePost.ascx) accepts a
System.Web.Mvc.ViewUserControl
and I'm not sure how to pass that from
all my views above.
I am not sure I understand what do you mean by "how to pass that from all my views above" but I am sure that you dont have to pass an instance of Post from your views. What is going on is that from your views you will invoke a controller action that creates the Post model object and then bind it to the CreatePost.ascx partial.
I'm also unsure know how to submit the
.ascx values to a certain URL (i.e.
/Topics/1/CreatePost), how do I tell
the submit button to post to that URL?
You have two options:
Inside your CreatePost.ascx partial you are probably using a form.
<% using (Html.BeginForm("action", "controller", FormMethod.Post, new {} )) { %>
If you use in the way I am showing you can change the first and the second params respectively to the names of the Action and the Controller that would habndle your submit.
The second option is using jQuery. Simply set an ID for your form and then
$("#myForm").submit(function(event) {
//post an ajax request to the server
});
Hope this helps!
P.S. To be able to reuse your CreatePost.ascx partial place it inside the shared view folder (where your master page is).
In regards to reusing a partial view which is not in the same view folder, use the following and pass in the model required, alternatively you can define a custom route for it.
<% html.RenderPartial("~/Views/<ControllerName>/<PartialViewName>.ascx", <model>);
#Marko
Another way would be to have in the PostController an Action like the following:
[HttpGet]
public ActionResult CreatePost( int topicId ) {
PostModel pm = _manager.CreateDefaultPost();
pm.TopicID = id;
return PartialView( "CreatePost", pm );
}
Then wherever you want to create a Post you can simply call this action that returns the strong-typed view for your new post.
Even if you have a supplementary http call over the network IMO this solution has the advantage to keep the initialization code of a new Post centralized to a single place.
From the View "point-of-view" the call to the action can be done when the user press the "New Post" button and then inject the received markup inside a modal dialog or in a place of your pleasure in the current page.
Hope it helps!

Categories

Resources