There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CategoryID - asp.net-mvc

I have found a lot of similar threads on this problem. But whatever I do, it never works for me.
The ONLY thing I want to achieve right now, is to fill a dropdown list with database values in a partial view, that's within a partial view. That is all, and this is driving me absolutely nuts. A user should be able to chose a category name in the dropdown list.
Here's my Controller Class:
public class AttributeController : Controller
{
private readonly IRepository<ClassLibrary.Entities.Attribute> _aRepository;
private readonly IRepository<Category> _cRepository;
public AttributeController() : this(new Repository<ClassLibrary.Entities.Attribute>(), new Repository<Category>())
{
}
public AttributeController(IRepository<ClassLibrary.Entities.Attribute> repo, IRepository<Category> repository)
{
_aRepository = repo;
_cRepository = repository;
}
//
// GET: /Attribute/
public ActionResult Index()
{
var attributes = _aRepository.GetAll();
var attributeViewModels = new List<AttributeViewModel>();
foreach (ClassLibrary.Entities.Attribute attribute in attributes)
{
var viewModel = new AttributeViewModel();
viewModel.Id = attribute.Id;
viewModel.AttributeName = attribute.Name;
attributeViewModels.Add(viewModel);
}
return View(attributeViewModels);
}
//
// GET: /Attribute/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Attribute/Create
public ActionResult Create()
{
ViewData["CategoryID"] = new SelectList(_cRepository.GetAll().ToList(), "Category_id", "Category");
IEnumerable<SelectListItem> items = _cRepository.GetAll().Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
});
ViewData["CategoryID"] = items;
return View();
}
//
// POST: /Attribute/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
And here's the index View:
#model IEnumerable<GUI.Models.AttributeViewModel>
#{
ViewBag.Title = "Attributes";
}
<div>
#Html.Partial("~/Views/Attribute/Create.cshtml", new GUI.Models.AttributeViewModel())
</div>
<h2>All existing Attributes</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.AttributeName)
</th>
<th></th>
</tr>
#if(Model != null)
{
foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.AttributeName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
}
</table>
Here's the partial View Within the index view:
#model GUI.Models.AttributeViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create an attribute for this Category</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.Partial("~/Views/Attribute/CategoryPartial.cshtml", new GUI.Models.CategoryViewModel())
<div class="form-group">
#Html.LabelFor(model => model.AttributeName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AttributeName)
#Html.ValidationMessageFor(model => model.AttributeName)
</div>
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And finally CategoryPartialView within the partial view that will contain the DropDown List where the user should be able to select a category Name.
#model GUI.Models.CategoryViewModel
#using GUI.Controllers
#using System.Collections.Generic
#{
//var categories = (IEnumerable<GUI.Models.CategoryViewModel>)ViewData["categories"];
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CategoryID", (IEnumerable<SelectListItem>)ViewData["CategoryID"])
</div>
</div>
}
The exception ALWAYS occurs when I'm debugging the application and it points to the #Html.DropDownList part. Claiming that "There is no ViewData item of type 'IEnumerable' that has the key 'CategoryID".
#Html.DropDownList("CategoryID", (IEnumerable<SelectListItem>)ViewData["CategoryID"]
I'm sorry for posting so many code blocks. But I would really like to solve this.I've beaten my head against the wall for hours with frustration, and any help would be greatly appreciated.

When you use #Html.Partial("~/Views/Attribute/CategoryPartial.cshtml", new GUI.Models.CategoryViewModel()) you are directly instantiating the partial view. The controller does not get called and is not responsible for generating the HTML markup string. Additionally, you are passing an empty view model (new GUI.Models.CategoryViewModel()). Since the controller does not get called, it does not get the data for the drop down list and, obviously, does not save it in your ViewData.
Use the #Html.Action helper instead:
<div class="form-group">
#Html.Action("Create", "Attribute")
<div class="form-group">
Change the Create action like this:
//
// GET: /Attribute/Create
public ActionResult Create()
{
ViewData["CategoryID"] = new SelectList(_cRepository.GetAll().ToList(), "Category_id", "Category");
IEnumerable<SelectListItem> items = _cRepository.GetAll().Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
});
ViewData["CategoryID"] = items;
return PartialView("CategoryPartial", new GUI.Models.CategoryViewModel());
}
Note: I don't know your entire structure, but I might be best to use this approach and to return a Lis<SelectListItem> model.

when calling:
#Html.Partial("~/Views/Attribute/Create.cshtml", new GUI.Models.AttributeViewModel())
you call the view directly with out passing throw the controller so the model you have there is an empty model!
try pass throw the controller to create you'r model and send it back as a view:
#Html.RenderPartial("YOUR CONTROLLER",model);

Related

issue with foreign key in asp.net mvc?

I am facing a referance issue
empid is not insert in the table when employee generate the experiance then not display the experiance data on the index page?
HomeController.cs
public class HomeController : Controller
{
private readonly dbozeeEntities dbemp;
public HomeController()
{
dbemp = new dbozeeEntities();
}
// GET: Home
public ActionResult Index()
{
var list = dbemp.employees.ToList();
return View(list);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(employee emp)
{
var create = dbemp.employees.Add(emp);
dbemp.SaveChanges();
return RedirectToAction("Experiance", new { empId = emp.empid }); //here going to experiance page
}
public ActionResult Experiance(employee emps)
{
//ViewData["empid"] = emps.empid;
return View(new experiance() { empid = emps.empid });
}
[HttpPost]
public ActionResult Experiance(experiance exp,employee emps)
{
//ViewData["empid"] = emps.empid;
var create = dbemp.experiances.Add(exp);
dbemp.SaveChanges();
return RedirectToAction("Index");
}
Index.cshtml
#model IEnumerable<DemoOzeeTechno.Models.employee>
#using DemoOzeeTechno.Models
#{
ViewBag.Title = "Index";
IEnumerable<experiance> exp = ViewData["empid"] as IEnumerable<experiance>;
}
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.empname)
</th>
<th>
#Html.DisplayNameFor(model => model.emailaddress)
</th>
<th>
#Html.DisplayNameFor(model => model.contactno)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.empname)
</td>
<td>
#Html.DisplayFor(modelItem => item.emailaddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.contactno)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.empid }) |
#*#Html.ActionLink("Details", "Details", new { id=item.empid }) |*#
#Html.ActionLink("Delete", "Delete", new { id=item.empid })
</td>
</tr>
}
</table>
<table>
<tr>
<th>CompanyName</th>
<th>YearOfExperiance</th>
</tr>
#if (ViewData["empid"] != null)
{
foreach (experiance ex in exp)
{
<tr>
<td>#ex.companyname</td>
<td>#ex.yearofexp</td>
</tr>
}
}
</table>
Experiance.cshtml
#model DemoOzeeTechno.Models.experiance
#{
ViewBag.Title = "Experiance";
}
<h2>Experiance</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>experiance</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.companyname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.companyname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.companyname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.yearofexp, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.yearofexp, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.yearofexp, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#* #Html.LabelFor(model => model.empid, "empid", htmlAttributes: new { #class = "control-label col-md-2" })*#
<div class="col-md-10">
#Html.HiddenFor(model => model.empid)
#*#Html.DropDownList("empid", null, htmlAttributes: new { #class = "form-control" })*#
#Html.ValidationMessageFor(model => model.empid, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Database Design:
experiance data inserted in table but issue is Does not Displaying the experiance data in index page
Watch Window:
empis is not insert in the table and experiance data not display on the page that is the issue??
First, you should know that ViewData get loss data while redirection from one action to another, So you have two options to pass empid from one Action to another one is to use Session and other is pass data in query string. So I would prefer a query string. So here is how you can do this.
First, you need to pass created empid to Experience action by the query string.
[HttpPost]
public ActionResult Create(employee emp)
{
var create = dbemp.employees.Add(emp);
dbemp.SaveChanges();
return RedirectToAction("Experiance",new{empId=emp.id}); //here going to experiance page
}
Now pass data to your view so that it post this id with newly created experience.
public ActionResult Experiance(int empId)
{
return View(new experiance(){empid=empId});
}
In the view you need a hidden field which will store this id into create experience form and submit along with experience fields.
#Html.HiddenFor(model=>model.empid)
Now in you Experience post-action you don't need to set empid explicitly it will get it from posted form values.
[HttpPost]
public ActionResult Experiance(experiance exp)
{
var create = dbemp.experiances.Add(exp);
dbemp.SaveChanges();
return RedirectToAction("Index");
}
Updated
To show the experience table on index page get all the experience list from the database and store it to ViewData.
// GET: Home
public ActionResult Index()
{
var list = dbemp.employees.ToList();
ViewData["empid"]=dbemp.experience.ToList();
return View(list);
}

View is expecting for viewmodel while List item has been passed to controller

Error::
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ProjDAL.Models.ViewModels.EmpViewModel]', but this dictionary requires a model item of type 'ProjDAL.Models.ViewModels.EmpViewModel'.
I am working on a mvc application. For one view which basically has a functionality for multiple parameter search. I am using same view for get and post method... It means i am passing 1 or more parameters to the textboxes and fetching the result using linq and mapping to a datatable.
After passing the parameters, the values are going to the controller and fetching the exact result using linq but the problem is coming when i am trying to map the linq result-set to my view.
Here is the code for the project -
Controller -
[HttpPost]
public ActionResult EmpSearch([Bind(Include = "employee,EmpID,PAN")] Get_EmpDetails_Result get_EmpDetails_Result)
{
var result = from emp in dbCollections.Employees
join nat in dbCollections.NationalID on emp.EmpID equals nat.EmpID
select new EmpViewModel
{
PAN = nat.pan,
EmpID = emp.EmpID,
employee = emp.Name
};
var searchRes = result
.Where(s => s.PAN.Contains(get_EmpDetails_Result.pan)
|| s.EmpID.Contains(get_EmpDetails_Result.empid)
|| s.employee.Contains(get_EmpDetails_Result.employee));
var modelSys = searchRes.ToList();
return View(modelSys);
}
View ::::
#model NewProjDAL.Models.ViewModels.EmpViewModel
#{
ViewBag.Title = "empDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
//////////// this part is for the multiple criteria search
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label>By EmpID</label>
<div class="col-md-10">
#Html.EditorFor(model => model.GetEmpDetails.FirstOrDefault().empid, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<label>By PAN</label>
<div class="col-md-10">
#Html.EditorFor(model => model.GetEmpDetails.FirstOrDefault().pan, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<label>By Name</label>
<div class="col-md-10">
#Html.EditorFor(model => model.GetEmpDetails.FirstOrDefault().employee, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-actions center">
<button type="submit" data-animation="pulse" class="btn btn-lg font-medium-1 btn-outline-teal mb-1 block-multiple-msgs buttonAnimation">
<i class="fa fa-check-square-o"></i> Go
</button>
</div>
</div>
}
//////////////////////////////this part is to fetch the result of the previously mentioned multiple search
#if (Model.EmpDetails.Count != 0)
{
<div class="table-responsive">
<table class="table table-striped table-bordered dom-jQuery-events compact" id="DataTbl">
<thead class="navbar-dark navbar-dark bg-blue-grey white">
<tr>
<th>
employee
</th>
<th>
PAN
</th>
<th>
empid
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.GetEmpDetails)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.employee)
</td>
<td>
#Html.DisplayFor(modelItem => item.PAN)
</td>
<td>
#Html.DisplayFor(modelItem => item.empid)
</td>
</tr>
}
</tbody>
</table>
</div>
}
It's told you exactly what the problem is. You've set up the view to accept a single EmpViewModel as the Model, but your controller is passing a List
You need to create a view model to represent the search criteria and the results
public class EmployeeSearchViewModel
{
public string EmpId { get; set; }
public string PAN { get; set; }
public string Employee { get; set; }
public List<EmpViewModel> Employees { get; set; } = new List<EmpViewModel>();
}
then in your controller method:
var modelSys = searchRes.ToList();
var viewModel = new EmployeeSearchViewModel
{
PAN = get_EmpDetails_Result.pan,
EmpId = get_EmpDetails_Result.empid,
Employee = get_EmpDetails_Result.employee
Employees = modelSys
};
return View(viewModel);
In the view:
#Model EmployeeSearchViewModel
Then your parameters display don't need to pull the EmpID, PAN, etc. from the collection, just from the view model, and you can bind your repeated results to the inner collection "Employees".

MVC ViewModel collections are null on postback

I have a view model which contains a class reference and 2 IEnumerable collections.
public class BuildingTypeViewModel
{
public Static_Item BuildingType { get; set; }
public IEnumerable<Reading_Type> ReadingTypes { get; set; }
public IEnumerable<Building_Type_Reading> BuildingReadings { get; set; }
}
I populate this ViewModel in the Edit action on the controller
public ActionResult Edit(int id)
{
Static_Item staticItem = db.Static_Item.Find(id);
BuildingTypeViewModel model = new BuildingTypeViewModel
{
BuildingType = staticItem,
ReadingTypes=db.Reading_Type.ToList(),
BuildingReadings = db.Building_Type_Reading.Where(bt => bt.UN_Building_Type == staticItem.UN_Building_Type).ToList()
};
return View(model);
}
Building type on the view model is a class with an ID and Description and the data would be something like this:
UN_Building_Type=1, Description = "Hospital"
The IEnumerable of Reading_Type's would be like this:
UN_Reading_Type = 1, Description = "Electric"
UN_Reading_Type = 2, Description = "Gas"
The IEnumerable of Building_Type_Readings would be like this:
UN_Building_Type_Readings=1, UN_Building_Type=1, UN_Reading_Type = 1, Typical=300, Good=150
UN_Building_Type_Readings=2, UN_Building_Type=1, UN_Reading_Type = 2, Typical=800, Good=400
I load this data into my view:
#model SSE.Enterprise.EE_Web_Portal.Models.BuildingTypeViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Static_Item</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.BuildingType.UN_Building_Type)
<div class="form-group">
#Html.LabelFor(model => model.BuildingType.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BuildingType.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BuildingType.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Building Readings</label>
<div class="col-md-10">
<table class="table">
<tr>
<th/>
<th>
#Html.LabelFor(model=>model.BuildingReadings.FirstOrDefault().Typical)
</th>
<th>
#Html.LabelFor(model => model.BuildingReadings.FirstOrDefault().Good)
</th>
</tr>
#foreach (var item in Model.ReadingTypes)
{
<tr>
<td>
#Html.Label(item.Description)
</td>
<td>
#Html.EditorFor(model => model.BuildingReadings.FirstOrDefault(b => b.UN_Reading_Type == item.UN_Reading_Type).Typical, new { htmlAttributes = new { #class = "form-control" } })
</td>
<td>
#Html.EditorFor(model => model.BuildingReadings.FirstOrDefault(b => b.UN_Reading_Type == item.UN_Reading_Type).Good, new { htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
}
</table>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Here is my edit postback method.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "BuildingType")] BuildingTypeViewModel model)
{
if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
When the page is posted back the 2 IEnumerable collections are null so I'm not able to save the data that has been entered.
Any idea?
Ta
First of all, by specifying the attribute Bind(Include = "BuildingType") you're telling MVC to only bind this single property. Remove the attribute, and MVC will try to bind your 2 IEnumerable collections.
Next, check your #Html.EditorFor calls. I'm not sure MVC can understand FirstOrDefault inside. Try avoiding LINQ selectors inside your view.
And after that, as #will mentioned, try changing IEnumerable to List.

Sessions in MVC 5 asp.net

I am doing a project about an Chinese food ordering system, and I am wanting show selected items in a view on another page. I am trying to use sessions, but I keep getting different errors, like "The model item passed into the dictionary is of type" and "object reference is not set to an instance of an object". How can I select the data, and show them in a different view? The project is linked up to a database, the DishID and other instances should be connected through the database.
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KinaRest.Models;
using KinaRest.View_Models;
using KinaRest.Infrastructure;
namespace KinaRest.Controllers
{
public class TakeawayController : Controller
{
private Basket basket = new Basket();
[ChildActionOnly]
public ActionResult BasketItemsList()
{
Basket basket = new Basket();
return View("_Basket", basket.Items);
}
// GET: /Takeaway/
private ChinaContext db = new ChinaContext();
[HttpGet]
public ActionResult Index()
{
return View(db.Dish.ToList());
}
[HttpPost]
public ActionResult Index(BasketItem basketItem)
{
//Repository repository = new Repository();
if (Session["Basket"] == null)
{
Session["Basket"] = new Basket();
}
else
{
basket = (Basket)Session["Basket"];
}
basket.AddItem(basketItem);
return View("Test");
}
}
}
Model 1: Basket
namespace KinaRest.Infrastructure
{
public class Basket
{
private List<BasketItem> items = new List<BasketItem>();
public List<BasketItem> Items { get { return items; } }
public void AddItem(BasketItem bi) {
items.Add(bi);
}
}
}
Model 2: BasketItem
namespace KinaRest.Infrastructure
{
public class BasketItem
{
public int DishId {get; set; }
public int Number { get; set; }
public decimal Price { get; set; }
}
}
In this view, we are trying to collect the data, such as the ID, the quantity(number) and price with a form:
#model IEnumerable<KinaRest.Models.Dish>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div class="form-group">
#using (Html.BeginForm())
{
foreach (var item in Model)
{
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.DishId)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Title)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Price)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Description)
</div>
<div class="col-md-10">
#Html.DisplayFor(modelItem => item.Type.Type1)
</div>
<img src="#Url.Content("~/content/images/" + item.Image)" />
#Html.EditorFor(model => item.Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => item.Number, "", new { #class = "text-danger" })
<input type="submit" value="Tilføj" class="btn btn-default" />
}
}
</div>
In this view, we are trying to access the sessions data:
#model List<KinaRest.Infrastructure.BasketItem>
#{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Test</h2>
<ul>
#foreach (var item in Model)
{
<li>
#Html.DisplayFor(modelItem => item.Number)
</li>
}
</ul>
and yes, I am new to MVC and I am still learning. Hope you guys can help.
[HttpGet]
public ActionResult Order(int id)
{
Dish dish = db.Dish.Single(d=> d.DishId == id); //database call here
BasketItem basketItem = new BasketItem(){DishId = dish.?, Number = dish.?, Price = dish.Price }; // create a new BasketItem
Basket basket; //create reference outside if block
//Repository repository = new Repository();
if (Session["Basket"] == null)
{
basket = new Basket();
Session["Basket"] = basket;
}
else
{
basket = (Basket)Session["Basket"];
}
basket.AddItem(basketItem);
return View("Test", basket.Items); //or return View(((Basket)Session["Basket"]).Items); // give the view the data
}
take out the class field basket. As far as i know the controller is instanciated every time when a request is to be processed
View for ordering
#model IEnumerable<KinaRest.Models.Dish>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<table>
<tr><th></th><th>Dish</th><th></th></tr>
#foreach(var item in Model)
{
<tr><td><img src="#Url.Content("~/content/images/" + item.Image)" /></td><td>#html.displayfor(item => item.Name)</td><td>#Html.ActionLink("Add", "Order", "TakeAway", new {id = item.DishId})</td></tr>
}
</table>

Pass object to partial view

I have this controller which fetches an object that I would like to render in a partial view:
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return View("_editPhoto");
}
Its the photo I would like to pass to my partial view.
I have this in my view:
#{
Html.RenderPartial("_editPhoto" );
}
How will I go about to pass my photo into the partial view in order for it to render in its parent?
EDIT:
This is how I pass the object to the controller:
#foreach (var item in Model.Photographys)
{
<li class="span3" style="text-align: center">
<div class="thumbnail thumbnail-1">
#Html.ActionLink(item.Name,
"EditPhoto", // <-- ActionMethod
new { id = item.Id }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
<h3 style="margin-bottom: 10px;">#item.Name</h3>
<div class="">
<div class="">
<img src="#item.ImgUrl" alt="" style="visibility: visible; opacity: 1;">
</div>
</div>
<section>
<p>#item.Description</p>
Read More
<p>#item.IsAccordion</p>
</section>
</div>
</li>
}
There seems a problem with this line however:
#{
Html.RenderPartial("_editPhoto" , Model);
}
Model gets underlined explaining that the Model passed into it (Photo) is not the right one..It seems that _editPhoto inherits the same Model as its parent maybe?
I managed to do this in the view:
#{
var i = new Photography();
Html.RenderPartial("_editPhoto", i);
}
The problem now is that the partialView gets rendered in a new window and not in its parent as I want it to.
UPDATE
Im gonna give this one last go, wont create a new question:
This is my controller passing a photo to a partial view:
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id) as Photography;
return PartialView("_editPhoto", photo);
}
My "mainview" contains this code to render the partial view with the photo getting sent to it:
<div class="form-control">
#{
var model = new Photography();
Html.Partial("_editPhoto",model);
}
</div>
This opens up a new window where my new photo shows up. I would like it to get rendered inside of its parents view the same way as it gets rendered automaticaly when i first visit the page...
Your controller action method should be:
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return View("EditPhoto",photo);
}
and your "EditPhoto" view should be:
#{ Html.RenderPartial("_editPhoto",Model); }
Update
Your controller action method should be:
public ActionResult Photos()
{
return View();
}
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return View(photo);
}
your "EditPhoto" should be view (not a partialview), on link click, "EditPhoto" action method is called and it returns the "EditPhoto" view
This questions seems related to one of your previous question.
Controller should be as follows;
public ActionResult EditPhoto(string id)
{
var photo = RavenSession.Load<ContentPage>(id);
return PartialView("_editPhoto", photo);
}
In your partial view _editPhoto, you can have the following code. I assume photo variable is a Photography object.
#model aPhoto_web.Models.AdminPages.Photography
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Photography</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
Thanks!

Resources