Problems with partialview data - asp.net-mvc

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}

Related

How can i pass multiple radio button values to controller in ASP.NET MVC?

I've a model that contains 3 tables in my view.
public class InExam
{
public AutoTests TheTest { get; set; }
public List<InTest> TheQuestions { get; set; }
public IEnumerable<Result> SingleQuee { get; set; }
}
First one made to get the detailed page, like "admin/AutoTests/id"
Second one made to get a list of questions linked to the page
Third one is to save radio button strings to post it back into the controller
my plan is to get (say) 20 questions that are linked with the detailed page, Adding 4 radio buttons for each question, and post back every selected button to the controller.
my view form :
#using (Html.BeginForm("Test", "Exams", new { id = Model.TheTest.id }, FormMethod.Post))
{
foreach (var item in Model.TheQuestions)
{
Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();
<div class="container" style="padding-top:50px;direction:rtl;">
<h4 style="text-align:right;font-weight:bold;">#item.Question</h4>
<div class="container">
<div class="row" style="direction:rtl;">
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "1" })
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "2" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer2</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "3" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer3</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "4" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer4</h5>
</div>
</div>
#Html.HiddenFor(m => singleQuee.Question)
</div>
</div>
</div>
}
<button class="btn botton" type="submit" onclick="return confirm('');">END</button>
}
i used this line "Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();" in my view because i can't use tuple foreach ( C# ver. 5 )
This is my controller code :
[HttpGet]public ActionResult Test(int? id)
{
using (KafoEntities db = new KafoEntities())
{
InExam model = new InExam();
model.TheTest = db.AutoTests.Where(x => x.id == id).FirstOrDefault();
model.TheQuestions = db.InTest.Where(x => x.UserEmail == currentUser.Email && x.ExamId == model.TheTest.id).OrderByDescending(x => x.id).Take(Convert.ToInt32(model.TheTest.QuestionsNumber)).ToList();
model.SingleQuee = db.Result.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Test(int? id, List<Result> singleQuee)
{
using (KafoEntities db = new KafoEntities())
{
int result = 0;
foreach (Result item in singleQuee)
{
Result sets = db.Result.Where(x => x.id == item.id).FirstOrDefault();
sets.Question = item.Question;
db.SaveChanges();
var check = db.InTest.Where(x => x.Question == item.Question).FirstOrDefault();
if (check != null)
{
if (item.Question == "1")
{
result++;
}
}
}
return RedirectToAction("Results", "Exams", new { Controller = "Exams", Action = "Results", id = done.id });
}
}
I first save the new string that came from the radio button value into the result record, then i call it back in the if condition to check it's value
The problem here is i get a
Object reference not set to an instance of an object.
when i post the test, it means that the list is empty, so i need to know what makes the radio buttons not working,
Thanks.
If you want to bind a List of object in Mvc, you should name the controller like "ModelName[indx].PropertyName". In your case it should be "singleQuee[0].Question".
Code Sample
var Indx = 0;
foreach (var item in Model.TheQuestions)
{
.....
var radioName = $"singleQuee[{Indx}].Question";
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
<input type="radio" name="#radioName" value="1" />
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
.....
}
Action Method

Partial View replaces Parent view

I'm working on web app developed in ASP.Net MVC, having a partial view which should be rendered inside its parent view.
Parent view has a HTML Dropdown, on-change event should bind respective data to partial view. But on selection change, the complete parent view is replaced with partial view (child view).
Parent View (Index.cshtml)
<h3>Please Select Group</h3>
#using (Html.BeginForm("EmployeeDeptHistory", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
if (ViewBag.DepartmentList != null)
{
#Html.DropDownList("DepartmentName", ViewBag.DepartmentList as SelectList, "-- Select --", new { Class = "form-control", onchange = "this.form.submit();" })
}
}
<div>
#{Html.RenderPartial("_EmployeeDeptHistory");}
</div>
Partial View (_EmployeeDeptHistory.cshtml)
#model IEnumerable<PartialViewApplSol.Models.EmployeeDepartmentHistory>
#if (Model != null)
{
<h3>Employees Department History : #Model.Count()</h3>
foreach (var item in Model)
{
<div style="border:solid 1px #808080; margin-bottom:2%;">
<div class="row">
<div class="col-md-2">
<strong>Name</strong>
</div>
<div class="col-md-5">
<span>#item.Name</span>
</div>
</div>
<div class="row">
<div class="col-md-2">
<strong>Shift</strong>
</div>
<div class="col-md-5">
<span>#item.Shift</span>
</div>
</div>
<div class="row">
<div class="col-md-2">
<strong>Department</strong>
</div>
<div class="col-md-5">
<span>#item.Department</span>
</div>
</div>
<div class="row">
<div class="col-md-2">
<strong>Group Name</strong>
</div>
<div class="col-md-5">
<span>#item.GroupName</span>
</div>
</div>
<div class="row">
<div class="col-md-2">
<strong>Start Date</strong>
</div>
<div class="col-md-5">
<span>#item.StartDate</span>
</div>
</div>
<div class="row">
<div class="col-md-2">
<strong>End Date</strong>
</div>
<div class="col-md-5">
<span>#item.EndDate</span>
</div>
</div>
</div>
}
}
I think the possible mistake is returning partial-view on drop down selection changed.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EmployeeDeptHistory(FormCollection form)
{
IEnumerable<EmployeeDepartmentHistory> empHistList;
using (IDbConnection con = new SqlConnection(connectionString))
{
empHistList = con.Query<EmployeeDepartmentHistory>("sp_StoredProc", new { DeptId = form["DepartmentName"] }, commandType: CommandType.StoredProcedure);
}
return View("_EmployeeDeptHistory", empHistList);
}
Instead of standard form submit, you need to use jQuery.ajax() function to load partial view inside HTML element without replacing parent view. Here are those steps:
1) Remove onchange event from DropDownList helper, and assign AJAX callback bound to change event:
View
#Html.DropDownList("DepartmentName", ViewBag.DepartmentList as SelectList, "-- Select --", new { #class = "form-control" })
jQuery (inside$(document).ready())
$('#DepartmentName').change(function () {
var selectedValue = $(this).val();
if (selectedValue && selectedValue != '')
{
$.ajax({
type: 'POST',
url: '#Url.Action("EmployeeDeptHistory", "ControllerName")',
data: { departmentName: selectedValue };
success: function (result) {
$('#targetElement').html(result); // assign rendered output to target element's ID
}
});
}
});
2) Remove FormCollection and use a string argument which has same name as AJAX callback argument, also make sure the action method returns PartialView:
Controller
[HttpPost]
public ActionResult EmployeeDeptHistory(string departmentName)
{
IEnumerable<EmployeeDepartmentHistory> empHistList;
using (IDbConnection con = new SqlConnection(connectionString))
{
empHistList = con.Query<EmployeeDepartmentHistory>("sp_StoredProc", new { DeptId = departmentName }, commandType: CommandType.StoredProcedure);
}
return PartialView("_EmployeeDeptHistory", empHistList);
}
3) Finally, don't forget to add ID for target element specified by AJAX callback's success part to load partial view:
View
<div id="targetElement">
#Html.Partial("_EmployeeDeptHistory")
</div>

ERROR:The model item passed into the dictionary is of type...but this dictionary requires a model item of type..."

I'm quite new to programming and I'm having some issues when i'm trying to run the program. I keep on getting this error:"The model item passed into the dictionary is of type 'DCMS.Models.Projects.Project', but this dictionary requires a model item of type 'DCMS.ViewModels.ProjectDetailsViewModel'".
This is my Controller:
public ActionResult GetProjectView(int id)
{
var projectDataAccess = new ProjectDataAccess();
var project = projectDataAccess.GetProject(id);
if (project == null) return PartialView("Error");
return View("ProjectView", project);
}
This is part of my View:
#model DCMS.ViewModels.ProjectListViewModel
#if (Model != null)
{
foreach (var project in Model.ProjectList)
{
<div class="accordion-container">
<h3 class="accordion-header">
#Html.ActionLink(project.Client.ClientName + " / " + project.ProjectName + " / " + project.ProjectNum ?? "<null>", "GetProjectView", new {id = project.Id})<span class="right">#Html.ActionLink("View Details", "GetProjectView", new {id = project.Id})</span>
</h3>
<div class="accordion-body">
<table class="accordion-details">
<tr class="accordion-evenrow">
<td class="accordion-header-column">
#Html.LabelFor(m => project.ProjectStatus)
</td>
<td class="accordion-value-column">
#project.ProjectStatus
</td>
This is the ProjectView:
#model DCMS.ViewModels.ProjectDetailsViewModel
#{
ViewBag.Title = "Project Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 id="breadcrumbs">#Html.ActionLink("Projects", "Index", "Project") > #(Model.Project.ProjectName ?? "<null>")/#Model.Project.ProjectNum </h2>
<div id="tabs">
<ul id="projectTabs" style="display:none;">
<li>Project Details</li>
<li>Client Pricing</li>
<li>Vendor Pricing</li>
<li>Status</li>
</ul>
<h2 style="margin:1px; font-size:20px;">#Model.Project.ProjectName /#Model.Project.ProjectNum</h2>
<div id="projectdetails">
#Html.Partial("Partial/EditProject")
</div>
<div id="pricing">
#Html.Partial("Partial/Pricing")
</div>
<div id="status">
#Html.Partial("Partial/ProjectStatus")
</div>
<div id="vendor">
#Html.Partial("Partial/VendorPricing")
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#projectTabs").show();
$("#tabs").tabs();
});
</script>
How can i pass the project which is of type Project to the View which is of type ProjectDetailsViewModel?
I would appreciate any help on this. Thanks.
As the Error States,
The model item passed into the dictionary is of type
'DCMS.Models.Projects.Project', but this dictionary requires a model
item of type 'DCMS.ViewModels.ProjectDetailsViewModel'
ViewModel and the Model passed should be same.
public ActionResult GetProjectView(int id)
{
ProjectDetailsViewModel _projectModel = new ProjectDetailsViewModel();
var projectDataAccess = new ProjectDataAccess();
var project = projectDataAccess.GetProject(id);
_projectModel.Project = project ;
if (project == null) return PartialView("Error");
return View("ProjectView", _projectModel );
}

The model item passed into the dictionary is of type 'BlogHomePageModel', but this dictionary requires a model item of type 'BlogHomePageModel'

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‘

Partial View MVC 4 in foreach loop

I'm using MVC 4 Ajax.BeginForm to update but it updates only the first element <div>
the View:
#model List<CSP1225.Models.Item>
#{
ViewBag.Title = "RecentItems";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/CSS/jobs.css" rel="stylesheet" />
#{ var convert = ViewBag.convert;
}
<div>
#foreach (var item in Model)
{
<div class="job-item">
<div class="inner">
<div class="span8 job-span">
<!--start of job list container div-->
<div id="ja-joblist">
<ol id="ja-searchjoblist">
<li class="job-item">#{ var PriceLE = #item.Price * convert;}
#using (#Ajax.BeginForm("_AddToCart", "Home", item, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "cart" }, null))
{
<!-- job item right section-->
<div class="inner">
<div class="ja-job-meta clearfix">
<span class="ja-job-category">#item.ItemName</span>
<span class="ja-job-category">#item.Price $</span>
<span class="ja-job-category">#PriceLE LE</span>
<div id="cart"></div>
<button type="submit">Add to Cart</button>
</div>
</div>
} </li>
<!-- end of job item right section-->
<!-- end of job item -->
</ol>
</div>
</div>
</div>
</div>
}
#Html.ActionLink("Go Back", "Index", "Home", new { #class = "makeneworder" })
</div>
and Controller:
public ActionResult _AddToCart(Item model)
{
ItemModel it = new ItemModel();
it.itemName = model.ItemName;
it.itemUrl = model.ItemURL;
it.quantity = 1;
it.unitprice = model.Price;
it.weight = (int)model.Weight;
it.ItemCategory =(int)model.CategoryID;
CartList.Add(it);
ViewBag.convert = (decimal)_db.Currencies.Where(x => x.Name == "Dollar").FirstOrDefault().Value;
ViewBag.list = CartList;
return PartialView();
}
Partial view :
<p>Added to Cart</p>
but the view returns multiple elements (as long as the list contains elements) when i click Add to Cart it updates the first element.. i understand that because u can not give another <div> the same id but how can i fix it?
you can create a dynamic ID like
#{ var divID = 1; }
then use it like
UpdateTargetId = "cart" + divID }
and
<div id="cart#divID" ></div>

Resources