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()); %>
Related
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.
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.
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%>
I'm with a problem, I have a ajax link that pass a parameter, but, the page that it opens does not need that parameter. The page only load 2 partial views, one of those need that parameter passed to the page to load the data correctly, and the other just need to load a form, so, don't need that parameter. How can i acheive this?
In order to do what you want, you will need to add the id to the ViewData construct.
var sysfunctions= UnisegurancaService.FunctionsRepository.All();
ViewData["NeededID"] = id
return View(sysfunctions);
then in your view where you render the partial
<%= Html.RenderPartial("GridFunction", (int)ViewData["NeededID"]) %>
Cast as required of course.
Whatever gets pushed in as the second param becomes the .Model in the partial. I would suggest also strongly typing your partials.
Try this:
<% Html.RenderPartial("GridFunction", new ViewDataDictionary {{"Id", ViewData["Id"]}}); %>
UPDATED:
And add this in your controller action:
ViewData["Id"] = Id;
UPDATED:
And in your GridFunction partial View you can access Id as:
<%= ViewData["Id"] %>
//Controller
public ActionResult EditFunctions(int id)
{
var sysfunctions= UnisegurancaService.FunctionsRepository.All();
return View(sysfunctions);
}
// This is the controller (it does no need the parameter "ID")
//This is the view "EditFunctions"
<div id="formFunction">
<% Html.RenderPartial("FormFunction"); %>
</div>
<div id="gridFunction">
<% Html.RenderPartial("GridFunction"); %> // The grid needs the ID to work correctly but its in the parent page not in the partial call....and the call is an ajax call
</div>
If some dependency of the page needs the parameter, then the page needs to know enough to pass the data in, so the page should be able to provide the data. Or, more simply, just add the parameter to the Page's viewdata and be done with it.
My action creates a strongly typed viewdata, which is passed to my view.
In the view, I pass the Model to the render partial method.
public ActionResult Index()
{
ViewDataForIndex vd = new ViewDataForIndex();
vd.Users = Users.GetAll();
return View(vd);
}
public class ViewDataForIndex: ViewData
{
public IList<User> Users {get;set;}
}
now in the view:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ViewDataForIndex>" %>
<% Html.RenderPartial("~/controls/blah.ascx", ViewData.Model); %>
and in blah.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
how do I access my model now?
if I wanted to create a strongly typed class for my ViewUserControl, how would I do that? inherit from?
One: Inside the ascx:
<%= Model.YourProperty %>
Two: Provide a type Argument to ViewUserControl:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>
I like #jfar's second approach better as it allows for easier modification if you ever decide to pass a more complex model to the view.
So you may pass a class that has multiple properties and/or more child objects.
If you inherit from the object now, then all you need to do is to inherit from your complex object and change one piece of code, as well as add the new properties, and your done.
More specifically to jfar's answer:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ViewDataForIndex>" %>
If your parent page has a model of type ViewDataForIndex, calling the child with the same ViewData.Model will also pass an object of type ViewDataForIndex.