how to pass parameters to partial view to show db content? - asp.net-mvc

I am getting my content from a database. How can i use partial views to show content on page using that database?
database table: Content
[Id, Content] these are 2 fields
i want to get the content from db using partial views.
How i will pass an id to a partial view and show the content in view page?

You could use Html.RenderAction:
public class MyController
{
[ChildActionOnly]
public ActionResult Foo(int id)
{
var content = GetContentFromDatabase(id);
return Content(content, MediaTypeNames.Text.Html);
}
}
And in your view include the partial:
<%= Html.RenderAction("foo", "mycontroller", new { id = 5 }) %>
Remark: RenderAction is part of the now released ASP.NET MVC 2 RTM. For ASP.NET MVC 1 you may take a look at the Futures assembly containing this extension method.

Inside your view, use the Html.RenderPartial function. There are a few different uses:
You can pass in a model to the partial view: <% Html.RenderPartial("partialName", model); %>
Or you can pass in a whole new ViewDataDictionary: <% Html.RenderPartial("partialName", viewData); %>
For the full documentation, see here.
EDIT: (Answer to comment):
I would include that data as part of you're view's model. For example, let's say in your model you have:
List<Person> People;
In your view, you want to loop through each one of these, and use a PartialView to display the details:
<% foreach( var p in Model.People){ %>
<p> <% Html.RenderPartial("personPartial", p); %> </p>
<%}%>
Now, your PartialView might look like:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Person>" %>
<%=Model.PersonName%>

Related

ASP.NET MVC - Html.RenderPartial issues

I have a usercontrol named "LoginUserControl.ascx" which I have placed in a master page.
Header of "LoginUserControl.ascx"
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MultiTechnologyWeb.Models.loginmodel>" %>
Then I used the below code to show the usercontrol in the masterpage.
<% Html.RenderPartial("LoginUserControl"); %>
On first run the page "index" is loaded.
Notice the header of the "index" page, no model is specified. Thus page load successfully
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MT.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
Now I click on the link to open register.aspx. I got the below error
The model item passed into the dictionary is of type 'MultiTechnologyWeb.Models.registermodel', but this dictionary requires a model item of type 'MultiTechnologyWeb.Models.loginmodel'.
Header of "register.aspx" page
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/MT.Master" Inherits="System.Web.Mvc.ViewPage<MultiTechnologyWeb.Models.registermodel>" %>
So to my understanding model is being interchanged, so anybody can please help me on how to resolve this issue
More Explanation.............LATEST
I have debug, i know that the crash is occuring after the actionresult for register is finished execution.
Code below is for actionresult "register"
public ActionResult register()
{
registermodel model;
//some code here
return View("register",model);
}
So i'm just returning one type of model that is "registermodel", Would it be possible to return another model such as "loginmodel" by using a list or array to return multiple models in the same view.
You should use <% Html.RenderAction("Logon","Account"); %> in your MasterPage instead of using RenderPartial and in this action you just return the login partial you want to use in the header
public ActionResult Logon(){
// do your stuff
return PartialView("LoginUserControl");
}
By this way you could pass the loginmodel to the LogInPartial and pass registermodel to the register page
Please not that RenderAction and RenderPartial are not the same.
RenderPartial will render only the view. While RenderAction will make a new MVC roundtrip, by making a new instance of the controller etc and returning the result.
To solve your issue you could pass in the MultiTechnologyWeb.Models.loginmodel where you call <% Html.RenderPartial("LoginUserControl"); %>. It would look like this:
<% Html.RenderPartial("LoginUserControl", new MultiTechnologyWeb.Models.loginmodel()); %>
Or:
<% Html.RenderPartial("LoginUserControl", Model.LoginModel); %>
If you're not wanting to send a model to your partial view, which I've wanted to do in the past, you do have to at least pass something to the RenderPartial method.
This was the only method I could find that allowed me to now have to pass a model. I tried passing null and it continued to pass the parent model
<% Html.RenderPartial("LoginUserControl", new ViewDataDictionary()); %>

Multiple partial views on one main asp.net

trying to put a strongly typed partial view on a homepage in asp.net but it wont seem to work it, here is my code
new to asp.net and partial views.
Controller :
public ActionResult VenuePartial()
{
ViewData["Message"] = _entities.VenuePartialList();
return View();
}
Repository :
public IEnumerable<Venue> VenuePartialList()
{
var list = from s in _entities.Venue
orderby s.name ascending
select s;
return list.ToList();
}
IRepository :
IEnumerable<Venue> VenuePartialList();
Index Page :
<%Html.RenderPartial("~/Views/Venue/VenuePartial.ascx");%>
Any help would be grateful asap please
regards T
Maybe you need to pass a model to this partial:
<% Html.RenderPartial("~/Views/Venue/VenuePartial.ascx", ViewData["Message"]); %>
And by the way WTF are you using ViewData["Message"] to pass a model instead of using a model and a strongly typed view:
public ActionResult VenuePartial()
{
return View(_entities.VenuePartialList());
}
and then:
<% Html.RenderPartial("~/Views/Venue/VenuePartial.ascx", Model); %>
This obviously assumes that your partial is strongly typed to IEnumerable<Venue>. If it is typed to a single Venue you might also consider using Editor/Display Templates. So in your main view:
<%= Html.DisplayForModel() %>
and in the corresponding display template (~/Views/Shared/DisplayTemplates/Venue.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.Venue>" %>
<span>
<%= Html.DisplayFor(x => x.SomePropertyOfVenue) %>
</span>
and now the display template will be rendered for each item of the model collection.

Reusable components in ASP.NET MVC

I have feature on my website (some UI and associated functionality) that I want to be able to reuse on multiple pages. For the purposes of this question, let's say it's a "Comments" feature.
There is an area in my application for Components and within the area are a controller: /Controllers/CommentController, and two partial views: /Views/Comment/Index.ascx (for listing comments) and /Views/Comment/Create.ascx (for creating comments).
CommentController looks something like this:
public class CommentController : Controller
{
[ChildActionOnly]
public ActionResult Index()
{
return PartialView(GetComments());
}
[HttpGet]
[ChildActionOnly]
public ActionResult Create()
{
return PartialView(); //this is wrong.
}
[HttpPost]
[ChildActionOnly]
public ActionResult Create(FormCollection formValues)
{
SaveComment(formValues);
return RedirectToAction("Index"); //this is wrong too.
}
}
Index Partial View:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<div>
<% foreach (var item in Model) { %>
<div>
<%: item.Comment %>
</div>
<% } %>
<%: Html.ActionLink("Add a Comment", "Create", "Comment", new { area = "Components" }, null) %>
</div>
Create Partial View:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<div>
<% using (Html.BeginForm())
{%>
Enter your comment:
<div>
<input type="text" name="comment" />
</div>
<p>
<input type="submit" value="Create" />
<% //also render a cancel button and redirect to "Index" view %>
</p>
<% } %>
</div>
The Index partial view is included in a view with RenderAction, like so:
<% Html.RenderAction("Index", "Comment", new { area = "Components" }); %>
This code doesn't work because the forms within the partial views submit to actions on the CommentsController that are marked [ChildActionOnly] (this is by design, I don't want the "Components" to be requested independently of a hosting page).
How can I make this "component" approach work, i.e. have a partial view that submits a form to change the state of a component within a page without losing the hosting page itself?
EDIT:
To clarify, the use of [ChildActionOnly] is not my problem here. If I remove the attribute from my action methods, my code only "works" in that it doesn't throw an exception. My "component" still breaks out of its hosting page when its form is submitted (because I'm telling the form to submit to the partial view's URL!).
You are making MVC fight itself by asking a form to target an action that is marked as ChildActionOnly.
My solution to this problem when I was designing a highly reusable wizard framework, was to NOT mark the actions as ChildActionOnly but instead to detect if the request was an ajax one or just a plain vanilla request.
The code for all this is packaged into a base controller class. In your derived controllers, you do something like:
[WizardStep(4, "Illness Details")]
public ActionResult IllnessDetails()
{
return Navigate();
}
Where the Navigate() method of the base controller has decided whether to return the full view or just the partial view, depending on whether it is, or isn't, an ajax request. That way, you can never return the partial view in isolation.
To ascertain if it is an Ajax request, I used a combination of Request.IsAjaxRequest() and TempData. The TempData is needed because my wizard framework implements the PRG pattern out of the box, so I need to persist the fact that the original post was an ajax one.
I guess this is just one solution and it took a bit of trial and error to get it right. But now I live happily ever after developing wizards like I was JK Rowling...
Use Ajax to post the partial.

ASP.NET MVC – Database Driven Menu

I have a database menu structure which I would like to add to the site.master file.
I’ve looked at other questions on StackOverflow but cannot get this to work on my website.
How do I add a User Control to the Site.Master file?
Menu.ascx
<%foreach (MainMenuSort mainMenuSort in (List<MainMenuSort>)ViewData["MainMenuSortListDisplay"])
{ %>
<li><%= Html.Encode(mainMenuSort.MainMenuId.MainMenuName)%></li>
<%foreach (SubMenuSort subMenuSort in (List<SubMenuSort>)ViewData["SubMenuSortListDisplay"])
{%>
<%if (mainMenuSort.MainMenuId.Id == subMenuSort.SubMenuId.MainMenu.Id)
{ %>
<li><%= Html.Encode(subMenuSort.SubMenuId.SubMenuName)%></li>
<%} %>
<%} %>
<%}%>
You need to use the Html.RenderPartial method in your master page.
You will need to set the MainMenuSortListDisplay and SubMenuSortListDisplay view data keys in whatever action is calling the view that uses your master page.
In your master use this
<% Html.RenderPartial("~/Views/Shared/Menu.ascx");
The path needs to be the app relative path to the control's folder. Typically these go under Shared. You can make the structure how you want below the Shared folder.
To make this technique stronger, use a strongly typed partial. In the question you would perhaps make a new class (MenuModel) with two generic collections as properties and place it in the models folder of the application. Then in the model's constructor call a method that populates the lists.
public class MenuModel
{
public IEnumerable<MainMenuSort> OuterList {get; set;}
public IEnumerable<SubMEnuSort> InnerList {get; set;}
public MenuModel()
{
VoidThatFillsTheInnerAndOuterList();
}
This will mean that you can do this in your controller
public ActionResult ShowAForm()
{
ViewData["MenuPartialData"] = new MenuModel();
return View();
}
Having set this key, your master page can use the overload of RenderPartial, like this
<% Html.RenderPartial(
"~/View/Shared/Menu.ascx",
(MenuModel)ViewData["MenuPartialData"]); %>
This assumes that your partial is strongly typed to the MenuModel class. Then in the partial you can use the model which rewrites your code slightly
<% foreach (MainMenuSort mainMenuSort in Model.OuterList) { %>
<li><%= Html.Encode(mainMenuSort.MainMenuId.MainMenuName)%></li>
<% foreach (SubMenuSort subMenuSort in Model.InnerList) {%>
<%if (mainMenuSort.MainMenuId.Id == subMenuSort.SubMenuId.MainMenu.Id)
{ %>
<li><%= Html.Encode(subMenuSort.SubMenuId.SubMenuName)%></li>
<%} %>
<%} %>
<%}%>
Hope that helps
Try something like
<% Html.RenderPartial("Menu") %>
EDIT: Corrected a typo
You could also do it as a HTMLHelper and in the MasterPage just call <%= Html.Menu() %>. Then in your HTMLHelper you have the code to get the database records and loop through them. Here is a link I found to get you started. Note my comments as there is a bug in the code example provided. I'm still having issues handling subitems of menus, I guess I need a recursive function or something??
With the help of this link. I was able to display a menu in the site.master page.

How do I pass a string to a partial view in ASP.NET MVC?

I have a search page that if there is results in the list it passes this list to a view.
However if there are no results I want to send the searched text to a no results found view.
How would I go about this?
You will need to have the searched text available as part of the model that is returned to the view. Then you have two options -
Using the RenderPartial will pass the returned view to the partial view so you can access the value you want from there.
Html.RenderPartial("PartialView");
Alternatively, you can pass the string as the model for the partial view using
Html.RenderPartial("PartialView", Model.SearchedText);
Which might make sense if you want to use the no results partial view with different models.
<%Html.RenderPartial("SimpleTrustGridViewer", ViewData["departmentGrid"]); %>
this passes an object ViewData["departmentGrid"] (this comes from viewdata of the non-partial view) to the partial view SimpleTrustGridViewer.
simplified:
<%Html.RenderPartial("myUserControl", myString); %>
And your partial view inherits like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
Then, in your partial view 'Model' will be the passed string.
The ViewDataDictionary passed from the controller to the view will be the same passed from the View to the Partial View. So if the string you want to pass is in the ViewDataDictionary you don't have to pass it.
<%=Html.RenderPartial("NorResultFound")) %>
But you can use the same view whether there were results or not:
<%if (Model.ResultCount!=0){ %>
<%foreach(var result in Model){ %>
<%= // display results %>
<%}}%>
<%else {%>
<p>There is no results for <%=ViewData["keyword"]%> </p>
<%} %>
I tried this and couldn't get it to work. Say I have
<div id="SearchBar">
<% using (Html.BeginForm("IndexNoJavaScript", "Home"))
{%>
<%= Html.TextBox("SearchTextBox", ViewData["SearchText"]) %>
<input type="submit" value="Search" /> <% } %>
</div>
<% Html.RenderPartial("SearchResults"); %>
And when I try to display the search text in this view like so:
<%= Html.TextBox("SearchedText", ViewData["SearchText"] ) %>
My text box is blank.
You can use jquery and load() action on div tag , insted of using partial; the result is similar.
The load() ajax method call on controller with the text that you want.
like:
$('#divId').load('url/'+ serch content );
Partial view unless you pass to it something else explicitly, has the same Model as parent view.
Two ways (you are talking about views, not partial views right?)
1) in your controller just call a different view in case of no results passing a string as model
2) create a model containing a search status (found x items, no match found, etc...) and a list of results to the same view, allowing the view to render the different results with a switch statement.

Resources