The model item passed into the dictionary is of type 'BlogHomePageModel', but this dictionary requires a model item of type 'BlogHomePageModel' - asp.net-mvc

I'm using Umbraco 7.04. I would post code but I can't determine what is causing the problem. I did make some edits to a class in my App_Code folder and my website started displaying this error. I reverted those edits but still get the error.
A coworker mentioned that .net can cache files so I tried recycling app pool and editing web.config to no avail.
EDIT: here is the code I believe was causing the problem, although it seemed to have gone away randomly.
BlogHomePage View
#inherits Umbraco.Web.Mvc.UmbracoViewPage<BlogHomePageModel>
#{
Layout = "BlogLayout.cshtml";
var BlogBackgroundImageCss = Html.Raw(HttpUtility.HtmlDecode(Model.BannerImageBackgroundImageCss));
var BlogHomeContent = Html.Raw(HttpUtility.HtmlDecode(Model.BlogHomeContent));
var AllTags = Html.Raw(HttpUtility.HtmlDecode(thunder.TagHelper.GetAllTags(Model.Content)));
var PagingHtml = Html.Raw(HttpUtility.HtmlDecode(Model.PagingHtml));
}
<div class="blog-area">
<div class="blog-banner-area" style="#BlogBackgroundImageCss" >
<span>#Model.BannerImageTitle</span>
</div>
<div class="blog-nav-area">
<button class="blog-nav-collapse-button"><span>Search</span></button>
<div class="blog-nav-inner-area">
#{ Html.RenderPartial("BlogHomeSearchInformation", Model); }
#{ Html.RenderPartial("BlogPostSearch"); }
#AllTags
#{ Html.RenderPartial("BlogHomeAside", Model); /*use partial to render blog post aside*/ }
</div>
</div>
<div class="blog-main-area">
<div class="blog-heading-area">
<div class="blog-heading-text-container">
#BlogHomeContent
<button class="blog-about-this-blog-expand-button">Read More</button>
</div>
</div>
#if (Model.Posts.Count() > 0) {
foreach (var Post in Model.Posts) {
Html.RenderPartial("BlogHomePostPartial", Post); /*use partial to render blog post content*/
}
#PagingHtml
} else {
<p>Sorry, but no posts matched your query.</p>
}
</div>
</div>
BlogHomeSearchInformationPartial
#inherits Umbraco.Web.Mvc.UmbracoViewPage<BlogHomePageModel>
#{
string SearchTerm = (!string.IsNullOrEmpty(Request.QueryString["s"])) ? Request.QueryString["s"] : "";
string TagTerm = (!string.IsNullOrEmpty(Request.QueryString["t"])) ? Request.QueryString["t"] : "";
}
<div id="blog-search-results-information">
#if (!string.IsNullOrEmpty(SearchTerm)) {
if (Model.TotalResults == 1) {
<p>Your search for "#SearchTerm" returned #Model.TotalResults result. Click here to return to home page.</p>
} else {
<p>Your search for "#SearchTerm" returned #Model.TotalResults results. Click here to return to home page.</p>
}
}
#if (!string.IsNullOrEmpty(TagTerm)) {
if (Model.TotalResults == 1) {
<p>There is #Model.TotalResults post tagged "#TagTerm". Click here to return to home page.</p>
} else {
<p>There are #Model.TotalResults posts tagged "#TagTerm". Click here to return to home page.</p>
}
}
</div>
BlogPostSearch
#inherits UmbracoTemplatePage
#{
string SearchTerm = "";
SearchTerm = Request.QueryString["s"];
}
<form role="search" method="get" id="searchform" action="/">
<div class="blog-search-area">
<input type="search" name="s" value="#SearchTerm">
<button type="submit">Search</button>
</div>
</form>
BlogPostAside
#inherits Umbraco.Web.Mvc.UmbracoViewPage<BlogHomePageModel>
#{
var AsideLinks = Html.Raw(HttpUtility.HtmlDecode(Model.AsideLinks));
}
#if (!string.IsNullOrEmpty(Model.AsideHeading) || !string.IsNullOrEmpty(Model.AsideSubheading) || !string.IsNullOrEmpty(Model.AsideContent) || !string.IsNullOrEmpty(Model.AsideLinks)) {
<div class="blog-contact-area">
<span class="blog-contact-heading">#Model.AsideHeading</span>
<span class="blog-contact-subheading">#Model.AsideSubheading</span>
<p>#Model.AsideContent</p>
#AsideLinks
</div>
}

Seems to me you have defined a special model on your view (or you did inherit form something).
Try to remove the #model and the #inherits from your view.

problem solved itself mysteriously :( After a little more research I believe it may be related to this question: The model item passed into the dictionary is of type ‘mvc.Models.ModelA’ but this dictionary requires a model item of type ‘mvc.Models.ModelB‘

Related

Umbraco 8 search function

I'm trying to implement a basic search functionality on Umbraco 8. So I created a search page, and here is my template:
#inherits Umbraco.Web.Mvc.UmbracoViewPage<ContentModels.Search>
#using ContentModels = Umbraco.Web.PublishedModels;
#{
Layout = "master.cshtml";
}
<div class="container">
#{
var searchQuery = Request.QueryString["query"];
if (!string.IsNullOrEmpty(searchQuery))
{
<div class="searchresults">
<p>Your search results for <strong>#searchQuery</strong></p>
<ul>
#foreach (var result in Umbraco.Search(searchQuery))
{
<li>
#result.Name
</li>
}
</ul>
</div>
}else{
<h1>No results</h1>
}
}
</div>
But I got a compilation error when trying to use Umbraco.Search() saying:
"UmbracoHelper" does not contain a definition for 'Search'.
Any ideas?
Thanks
UPDATE:
You need to use Umbraco.ContentQuery.Search instead of Umbraco.Search
Instead of Umbraco.Search, try using Umbraco.ContentQuery.Search.
It will work
refer link,
https://our.umbraco.com/forum/using-umbraco-and-getting-started/96691-umbraco-search-function

DNN MVC Module not posting file back

I am building a small DNN MVC module whereby I need a user to upload file which will be processed server side.
When the form is posted back, the view model is posted back fine, but the file never is. Request.Files is always 0.
I even simplified it so all I had on the module was a simple file input and submit button but that failed as well.
I would hate to have to revert back to .ascx controls to get this to work.
I am testing this as an unregistered user, therefore there is no authentication checking in the controller.
See code below:
View
#inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<NM.Modules.FlexEventsCreate.Models.FlexEventViewModel>
#using DotNetNuke.Web.Mvc.Helpers
<input type="file" id="fileUp"/>
<input type="submit" id="btnSubmit" />
Controller
[DnnHandleError]
public class ItemController : DnnController
{
[HttpPost]
public ActionResult ShowForm(FlexEventViewModel flexEvent)
{
if (ModelState.IsValid)
{
var file = Request.Files;
if (file.Count != 0)
{
//do something
}
//return RedirectToDefaultRoute();
}
return View(flexEvent);
}
}
The rendered DNN HTML looks like this (I have simplified it)
<form method="post" action="/Test" id="Form" enctype="multipart/form-data">
<!-- Begin Content areas -->
<div>
<div class="row">
<div class="medium-9 columns">
<div id="dnn_LeftPane">
<div class="DnnModule DnnModule-DnnModule-747">
<a name="747"></a>
<div class="DnnF_Title_h1 SpacingBottom">
<h1><span id="dnn_ctr747_dnnTITLE_titleLabel" class="TitleH1"></span>
</h1>
<div id="dnn_ctr747_ContentPane">
<!-- Start_Module_747 -->
<div id="dnn_ctr747_ModuleContent">
<div id="dnn_ctr747_ShowForm_Prog" class="RadAjax RadAjax_Default" style="display:none;">
<div class="raDiv">
</div>
<div class="raColor raTransp">
</div>
</div>
<div class="RadAjaxPanel" id="dnn_ctr747_dnn_ctr747_ShowForm_UPPanel">
<div id="dnn_ctr747_ShowForm_UP">
<!-- 2013.2.717.40 -->
<div id="mvcContainer-747">
<input type="file" id="fileUp">
<input type="submit" id="btnSubmit">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
I did do an upload in an MVC module using the dropzone jquery component - which may help you. See my sample Restaurant Menu project on github.
First, include the dropzone script and css:
#using DotNetNuke.Web.Client.ClientResourceManagement
#{
ClientResourceManager.RegisterStyleSheet(Dnn.DnnPage, "~/DesktopModules/MVC/DotNetNuclear/RestaurantMenu/Resources/dropzone/css/dropzone.css");
ClientResourceManager.RegisterScript(Dnn.DnnPage, "~/DesktopModules/MVC/DotNetNuclear/RestaurantMenu/Resources/dropzone/js/dropzone.min.js", 100);
}
Then place a container div for the upload component:
<div id="dZUpload" class="uploadform dropzone no-margin dz-clickable">
<div class="dz-default dz-message"></div>
</div>
Initialize the component and tell it what type and how many files can be uploaded:
$("#dZUpload").dropzone({
acceptedFiles: "image/jpeg,image/png,image/gif",
url: '#Url.Action("Upload", "Menu")',
maxFiles: 1, // Number of files at a time
maxFilesize: 1, //in MB
addRemoveLinks: true,
maxfilesexceeded: function (file) {
alert('You have uploaded more than 1 Image. Only the first file will be uploaded!');
},
success: function (response) {
}
});
Change the acceptedFiles to the mimetypes you are restricting ("application/pdf", etc). Change the maxFiles to limit how many files they can upload at a time.
Write an MVC controller action to respond to the Dropzone file upload url. You can see it expects an action method "Upload" on the controller "Menu" (MenuController.Upload):
public JsonResult Upload()
{
string imageUrl = string.Empty;
string imgPath = Server.MapPath("~/Portals/0/Restaurant/");
if (!Directory.Exists(imgPath))
{
Directory.CreateDirectory(imgPath);
}
foreach (string s in Request.Files)
{
var file = Request.Files[s];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(imgPath, fileName);
file.SaveAs(path);
imageUrl = string.Format("/Portals/0/Restaurant/{0}", fileName);
}
}
return Json(new { img = imageUrl, thumb = imageUrl });
}

Problems with partialview data

I have a problem with a partial view. The first time when it is rendered everything is ok, but after that some data is loosed.
This is how my page should look: this is when the partial view is rendered the first time
but when I'm clicking on a category to check his subcategories, the image is null, it is not visible anymore. (only the name is visible)
This is my partial view:
#model IEnumerable<OnlineCarStore.Models.CategoriesVM>
<div class="container">
<div class="row">
#using (Html.BeginForm("SubCategories", "Product"))
{
<div class="list-group col-sm-3" style="width:280px;">
#{var selected = string.Empty;
if (#HttpContext.Current.Session["selectedCar"] == null)
{
selected = string.Empty;
}
else
{
selected = #HttpContext.Current.Session["selectedCar"].ToString();
}
foreach (var c in Model)
{
<a href="#Url.Action("SubCategories", "Product", new { selected = #selected, id = #c.ID, category = #c.CategoryName })" class="list-group-item">
<span> #c.CategoryName</span>
</a>
}
}
</div>
<div class="col-sm-9">
#foreach (var c in Model)
{
<div class="card-group" style="width:200px; display: inline-block">
<div class="card card">
<a href="#Url.Action("SubCategories", "Product", new { selected = #HttpContext.Current.Session["selectedCar"].ToString(), id = #c.ID, category = #c.CategoryName })" id="linkOnImg" class="card-group">
<img class="card-img-top center-block" src="#string.Format("../content/images/categories/{0}.jpg", #c.AtpID)" alt=#c.CategoryName style="padding-top: 5px">
<div class="card-text text-center">
<p class="category-card-title ">
<span class="text-muted">#c.CategoryName</span>
</p>
</div>
</a>
</div>
</div>
}
</div>
}
</div>
and this is the Subcategoris view, where the partial view is rendered second time:
<div class="container">
<div class="row">
#Html.Partial("/Views/Home/CategorieTypes.cshtml");
Here is the Product controller Subcategories method:
public ActionResult SubCategories(string selected, int id, string category)
{
List<CategoriesVM> listOfCategories = new List<CategoriesVM>();
var list = db.Categories.ToList();
var root = list.GenerateTree(c => c.ID, c => c.ParentId).ToList();
TreeItem<Categories> found = null;
var test = new TreeItem<Categories>();
foreach (var rootNode in root)
{
found = TreeGenerator.Find(rootNode, (n) => n.Item.ID == id);
if (found != default(TreeItem<Categories>))
{
test = found;
break;
}
}
foreach (var item in found.Children.ToList())
{
CategoriesVM categoryv = new CategoriesVM();
categoryv.ID = item.Item.ID;
categoryv.AtpID = item.Item.AtpID;
categoryv.Childrens = item.Children.ToList();
categoryv.CategoryName = item.Item.AtpName;//.Name;
listOfCategories.Add(categoryv);
}
SiteMaps.Current.CurrentNode.Title = selected + " " + category;
var tests = found.Children.ToList();
if (found.Children.ToList().Count == 0 )
{
return View("Index");
}
else
{
return View("SubCategories", listOfCategories);
}
}
I've checked in developer tool if the source for the image is correct, and although it is correct, the image is not showed:
Can you please help me in this problem? What I do wrong? Why the images don't appear after the first render of the partial view? Thanks in advance!
The path of the partial view is /Views/Home/CategorieTypes.cshtml and the path of the images is /Content/images/categories. In the partial view you are using ../content/images/categories/ as the path of the images which means that it will search for the path /Views/Content/Images/Categories which is invalid.
Remove the two dots in the src property and add a ~ so it will be like: ~/Content/Images/Categories/{img}.
or
Add one more ../ in order to go one level down to the directory like:
../../Content/Images/Categories/{img}

MVC Layout Navbar Active Hide/Show DIV

So i am going off of this example:
better way to get active pages
What I'm trying to accomplish in my _Layout.cshtml is this:
<div id="navbar">
<div><img src="~/Images/home_on.png" /></div>
<div><img src="~/Images/home_off.png" /></div>
<div><img src="~/Images/contact_on.png" /></div>
<div><img src="~/Images/contact_off.png" /></div>
</div>
The navbar div changes depending on the active page. If its home, then show "home_on.png" div. If its not display "home_off.png" and so forth.
I've used this in the past.
Declare at the top of the layout:
#{
var currentController = ViewContext.RouteData.Values["controller"] as string ?? string.Empty;
var currentAction = ViewContext.RouteData.Values["action"] as string ?? string.Empty;
string getImageSource(string basePath, string controller, string action)
{
var onOrOff = currentController.Equals(controller, StringComparison.OrdinalIgnoreCase) && currentAction.Equals(action, StringComparison.OrdinalIgnoreCase) ? "on.png" : "off.png";
return string.Format("{0}_{1}", basePath, onOrOff);
}
}
Then you can render the appropriate image based off the expected controller and action:
<div id="navbar">
<div><img src="#(getImageSource("~/Images/home", "Home", "Index"))" /></div>
<div><img src="#(getImageSource("~/Images/contact", "Home", "Contact"))" /></div>
</div>
I assume that the base ~/Home URL is going to the Index action on the HomeController, and that ~/Home/Contact is going to the Contact action on the HomeController.

How to Load Partial Views with Jquery UI Tab by passing parameters?

I have a parent page (DistributionReview.aspx) that has a Deposit Date to select using DatePicker.
Just below I have two tabs(*DistributionByType* and DistibutionByStatus) that I want to load PartialViews. Here the parameter to the PartialView is DepositDate.
And I have a custom ViewModel called DistributionReviewModel that the parent page is implementing.
I am coming across articles that are directly loading static partial views(Ex:
http://www.kevgriffin.com/blog/index.php/2010/02/23/using-jquery-tabs-and-asp-net-mvc-partial-views-for-ajax-goodness/
). But I am looking for any code sample/articles by passing parameter?
Appreciate if anyone can share code samples to pass parameters and load the partialview both when the TabSelection is changed and and DepositDate is changed.
Thanks for your time.
Html Code:
<script type="text/javascript">
$(function () {
//tab
$("#divDistributionReview").tabs();
$("#fileDepositDate").datepicker(); //DateTime Picker
var depositDate = $("#fileDepositDate").val();
});
<div id="container" >
<% using (Html.BeginForm("frmDistributionReview", "DistibutionReview"))
{ %>
<div> Select a Date: <input type="text" id="fileDepositDate" name="datepicker" value='<%= ViewData["FileDepositDate"] %>' /></div>
<div id="divDistributionReview">
<ul>
<li>Distribution Type</li>
<li>Status</li>
</ul>
</div>
<%} %>
</div>
C# Code:
public ActionResult DistributionReview()
{
ViewData["FileDepositDate"] = DateTime.Now.ToShortDateString();
var view = View(ApplicationConstants.DistributionReviewViewName, new MegaLockbox.Web.ViewModels.DistributionByTypeViewModel(securityManager, distributionReviewDataAdapter, Convert.ToDateTime(ViewData["FileDepositDate"])));
return view;
}
public ActionResult DistributionByType(string id)
{
DateTime depositDate;
var view = new PartialViewResult();
if (DateTime.TryParse(id , out depositDate))
{
view = PartialView(ApplicationConstants.DistributionByTypeViewName, new MegaLockbox.Web.ViewModels.DistributionByTypeViewModel(securityManager, distributionReviewDataAdapter, depositDate));
}
return view;
}
public ActionResult DistributionByStatus(string id)
{
DateTime depositDate;
var view = new PartialViewResult();
if(DateTime.TryParse(id, out depositDate) )
{
view = PartialView(ApplicationConstants.DistributionByStatusViewName, new MegaLockbox.Web.ViewModels.DistributionByTypeViewModel(securityManager, distributionReviewDataAdapter, depositDate));
}
return view;
}
here you have nice guide how to do this:
http://ericdotnet.wordpress.com/2009/03/17/jquery-ui-tabs-and-aspnet-mvc/
if you have any questions.. let us know:)
PS you can download the example, and play with it
Html for tab headers
<li><a onclick="LoadTabData('type')" href="/DistributionReview/DistributionByType">Distribution Type</a></li>
<li><a onclick="LoadTabData('status')" href="/DistributionReview/DistributionByStatus">Status</a></li>
Jquery function
function LoadTabData(type){
if(type='type')
$.post("YourController/DistributionByType", { id: $("#fileDepositDate").val()},
function(data) {
$(#"yourByTypeTabDiv").html(data);
});
}else{
$.post("YourController/DistributionByStatus", { id: $("#fileDepositDate").val()},
function(data) {
$(#"yourByStatusTabDiv").html(data);
});
}
Also this will work.
<div id="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<div id="tab-1">
#Html.Partial("_PartialViewForTab1", Model)
</div>
<div id="tab-2">
#Html.Partial("_PartialViewForTab2", Model)
</div>
<div id="tab-3">
#Html.Partial("_PartialViewForTab3", Model)
</div>
</div>

Resources