Calling Partial View from Home/Index problem - asp.net-mvc

I am creating a web page that displays 3 different kind of followers (Red, Blue, Yellow) and a Filter form that users can use to filter.
For instance, if the customer selects a Red option from the dropdown list, I wanna show them only the red followers.
I am creating the select part for now, but I am getting an error which reads like this.
The controller for path '/' was not found or does not implement IController.
This is the
AND this is the FilterController:
public class HomeController : Controller
{
private asp6Entities db = new asp6Entities();
public ActionResult Index()
{
var allFlowers = db.FLOWERs.ToList();
List<FLOWER> result = new List<FLOWER>();
foreach (var flower in allFlowers)
{
FLOWER model = new FLOWER();
model = flower;
result.Add(model);
}
return View(result);
}
public ActionResult About()
{
ViewBag.Message = "Our History";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Main Store and Distribution Center.";
return View();
}
[HttpPost]
public ActionResult Index(FilterModel fromColorFilter)
{
string SelectedColor = (fromColorFilter.ColorSelected);
var allFlowers = db.FLOWERs.ToList();
List<FLOWER> result = new List<FLOWER>();
foreach (var flower in allFlowers)
{
if (flower.COLOR.COLOR_NAME == SelectedColor)
{
FLOWER model = new FLOWER();
model = flower;
result.Add(model);
}
}
return View(result);
}
}
THis is the Filter Controller:
public class FilterController : Controller
{
// GET: FilterModel
private asp6Entities db = new asp6Entities();
public ActionResult Index()
{
FilterModel model = new FilterModel();
var color = db.COLORs.ToList().Select(s => new SelectListItem
{
Text = s.COLOR_NAME,
Value = s.COLOR_ID.ToString()
});
return PartialView("~/Views/Shared/_FilterForm.cshtml", new FilterModel { AllColorOptions = color});
}
}
And This is the FilterMethod :
public class FilterModel
{
//declaring the colors selection
public string ColorSelected { get; set; }
//Creating the Size selection
public string SizeSelected { get; set; }
//Creating the starting price selection
public int StartingPriceSelection { get; set; }
//Creating Ends price Selection
public int EndingPriceSelection { get; set; }
//creating IEnumerable of all color options
public IEnumerable<SelectListItem> AllColorOptions { get; set; }
//creating IEnumerable of all Size Options
public IEnumerable<SelectListItem> AllSizeOptions { get; set; }
//creating IEnumerable of Starting Price Options
public IEnumerable<SelectListItem> AllStartingPriceOptions { get; set; }
//creating IEnumerable of Ending Price Options
public IEnumerable<SelectListItem> AllEndingPriceOptions { get; set; }
}
This is the Home Index:
In this Home Index
#Html.Action("Index","FilterForm");

yes this is the best solution
#Html.Action("Index","Filter");

You should change the razor call to this
#Html.Action("Index","Filter");
Your controller is FilterController, therefore, you should use "Filter" as the second parameter, not "FilterForm"

Related

Unable to Auto mapping in sitecore MVC(Razoe VIew) help of glass mapper

Am using controller rendering, I created one model called Footer.cs and it has below properties.
[SitecoreType(TemplateId = "{1044CFB5-2B85-4A8D-9DCC-34764D2AF5B3}", AutoMap = true)]
public class Footer
{
public virtual Item Item { get; set; }
[SitecoreField(FieldName ="Copyright Text First",FieldType = SitecoreFieldType.SingleLineText)]
public virtual string CopyrightTextFirst { get; set; }
[SitecoreField(FieldName ="Copyright Text Last",FieldType = SitecoreFieldType.SingleLineText)]
public virtual string CopyrightTextLast { get; set; }
}
In My Controller:
public ActionResult FooterTemplate()
{
ISitecoreContext ctx = new SitecoreContext();
var model = ctx.GetCurrentItem<Footer>();
return View(model);
}
But, always getting null result, please help me any one.
You can use:
public ActionResult FooterTemplate()
{
ISitecoreContext ctx = new SitecoreContext();
var model = ctx.GetCurrentItem<Footer>(RenderingContext.Current.Rendering.DataSource);
return View(model);
}

Entity framework will replace a newly added record , with a record created inside the action method

I want to implement this simple scenario ,which I though EF will support out of the box.
I have a parent record named (Skill) and I am adding child records named (LinktoKB) to it. Now after adding a new LinktoKB, I want to return a view containing the up-to-date list of LinkToKBs (inclusing the newly added one).
Now my Post action method to add new LinktoKB is :-
[HttpPost]
[ValidateAntiForgeryToken]
[CheckUserPermissions(Action = "Edit", Model = "Skill")]
public async Task<ActionResult> AddKBLink(AssignKBLinksToSkill assignkblinkToSkill)
{
try
{
if (assignkblinkToSkill.LinkToKB == null)
{
return HttpNotFound();
}
if (ModelState.IsValid)
{
unitofwork.SkillRepository.AddKBLinkToSkill(assignkblinkToSkill, unitofwork.StaffRepository.GetLoginUserName(User.Identity.Name));
await unitofwork.Save();
//i have removed the values from the model state to prevent showing validation error "that the URL and name is required after succfully adding a new link"
// also to show the modified values and not the binded values
string oldlinkURL = assignkblinkToSkill.LinkToKB.URL;
ModelState.Clear();
var skillAfterAddingKBLink = await unitofwork.SkillRepository.FindSkill(assignkblinkToSkill.Skillid, r => r.LinkToKBs);
assignkblinkToSkill.LinktoKBList = skillAfterAddingKBLink.LinkToKBs.ToList(); //get the new lsit from DB after addign the new link
assignkblinkToSkill.LinkToKB.URL = "http://";//reset the values , so that user will not get old vlues
assignkblinkToSkill.LinkToKB.Name = String.Empty;
if (Request.IsAjaxRequest())
{
TempData["Partialmessage"] = string.Format("{0} URL have been Added", oldlinkURL);
return PartialView("AddKBLink", assignkblinkToSkill);
}
TempData["message"] = string.Format("{0} URL have been Added", oldlinkURL);
return View("AddKBLink", assignkblinkToSkill);
}
}
And my repository methods are:-
public async Task<Skill> FindSkill(int id, params Expression<Func<Skill, object>>[] includeProperties)
{
var query = context.Skills.AsQueryable();
if (includeProperties != null || includeProperties.Count() != 0 || includeProperties[0].Name == "0")
query = includeProperties.Aggregate(query, (current, include) => current.Include(include));
return await query.SingleOrDefaultAsync(a => a.SkillID == id);
}
&
public void AddKBLinkToSkill(AssignKBLinksToSkill assignKBLinkToSkill,string username)
{
var skill = context.Skills.SingleOrDefault(a=>a.SkillID == assignKBLinkToSkill.Skillid);
skill.LinkToKBs.Add(assignKBLinkToSkill.LinkToKB);
skill.Modified = System.DateTime.Now;
skill.ModifiedBy = staffrepo.GetUserIdByUserName(username);
context.Entry(skill).State = EntityState.Modified;
}
Currently I am getting a very strange behavior is that , the list that is returned to the view will not contain the newly added LinkToKB value and it will be replaced by the following value:-
assignkblinkToSkill.LinkToKB.URL = "http://"
so can anyone advice on this please, although I am explicitly retrieving the LinkToKB list from database?
visual studio will how the following at two different stages:-
First this is the newly added LinkToKB:-
Second EF have replace it with the value inside the action method:-
I spend the whole day trying to understand what is going on ... and if i removed these lines:-
assignkblinkToSkill.LinkToKB.URL = "http://";//reset the values , so that user will not get old vlues
assignkblinkToSkill.LinkToKB.Name = String.Empty;
i will get the new up-to-date list correctly (but i need them)..
I have two model classes (Skill & LinktoKB):-
public partial class Skill
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Skill()
{
this.SkillLevels = new HashSet<SkillLevel>();
this.SkillLevelStaffs = new HashSet<SkillLevelStaff>();
this.Customers = new HashSet<Customer>();
this.LinkToKBs = new HashSet<LinkToKB>();
this.SkillVersionHistories = new HashSet<SkillVersionHistory>();
this.Skill1 = new HashSet<Skill>();
this.Skills = new HashSet<Skill>();
}
public int SkillID { get; set; }
public string Name { get; set; }
//code goes here
public virtual SkillStatu SkillStatu { get; set; }
public virtual SkillType SkillType { get; set; }
public virtual ICollection<LinkToKB> LinkToKBs { get; set; }
}
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public LinkToKB()
{
this.Skills = new HashSet<Skill>();
}
public int LinkToKBID { get; set; }
public string URL { get; set; }
public string Name { get; set; }
public virtual ICollection<Skill> Skills { get; set; }
}
and the following viewModel class:-
public class AssignKBLinksToSkill
{
public ICollection<LinkToKB> LinktoKBList { set; get; }
public LinkToKB LinkToKB { set; get; }
public int Skillid { set; get; }
}
In your code there's always one assignkblinkToSkill.LinkToKB instance. When it enters the method it's got some value that you store in the database. Later you re-assign its value to be "http://".
But this is still the instance that you added to the list skillAfterAddingKBLink.LinkToKBs!
You only have to create a new instance in the view model:
assignkblinkToSkill.LinkToKB = new LinkToKB();
assignkblinkToSkill.LinkToKB.URL = "http://";

ViewModel Inheritance for different actions with Twitter Bootstrap MVC 4

I'm trying to create a ViewModel in MVC that allows me to switch between the display format and the edit format.
I can get the Controller to select the correct version of the ViewModel and all the properties for the inherited class and base class show in the debugger.
When the ViewModel is passed to the view, only the properties from the inherited class show up.
Can this approach work or should I create two seperate ViewModels?
ViewModel:
public partial class HouseholdViewModel
{
public int Id { get; set; }
public int familyID { get; set; }
public string entityName { get; set; }
public System.DateTime attachmentDate { get; set; }
}
public partial class DisplayHouseholdViewModel : HouseholdViewModel
{
public string phone { get; set; }
}
public partial class CreateHouseholdViewModel : HouseholdViewModel
{
public string familyPhoneCode { get; set; }
public string familyPhone { get; set; }
}
Controller (snippet):
public class HouseholdController : Controller
{
private WhatWorksEntities db = new WhatWorksEntities();
//return viewmodel object
private string displayView = "displayView";
private string createView = "createView";
public IEnumerable<object> GetModel(string view)
{
if (view == displayView)
{
var householdView = (from h in db.tHouseholds
select new DisplayHouseholdViewModel
{
Id = h.householdID,
familyID = h.familyID,
entityName = h.tEntity.entityName,
attachmentDate = h.attachmentDate,
phone = h.familyPhoneCode + " " + h.familyPhone
}).AsEnumerable();
return (householdView);
}
else
{
var householdView = (from h in db.tHouseholds
select new CreateHouseholdViewModel
{
Id = h.householdID,
familyID = h.familyID,
entityName = h.tEntity.entityName,
attachmentDate = h.attachmentDate,
familyPhoneCode = h.familyPhoneCode,
familyPhone = h.familyPhone
}).AsEnumerable();
return (householdView);
}
}
//
// GET: /Household/
public ActionResult Index()
{
var householdView = GetModel(displayView).Cast<DisplayHouseholdViewModel>();
return View(householdView);
}
The view that is returned doesn't display the phone property:
---EDIT to show debugger with phone data---
Debug view:
In your view you need some logic to display the field -
#Html.LabelFor(l => l.Phone, "Phone")
#Html.DisplayFor(p => p.Phone)
And at the top you need to make sure you are displaying the proper view model
#model YourNamespace.ViewModels.DisplayViewModel
If you are trying to change on the same view between two ViewModels you will need to create two separate partial views and toggle their display settings

Chaining multiple classes in a MVC4 view

Let's say I have a model like this (simplified from the original):
public class Location
{
public int ID { get; set; }
public string BinNumber { get; set; }
}
public class Item
{
public int ID { get; set; }
public string Description { get; set; }
public virtual Location Bin { get; set; }
}
public class LineOnPickList
{
public int ID { get; set; }
public virtual Item Item { get; set; }
}
The usual thing to do here on the LineOfPickList Create view would be to have a dropdownlist that listed all the Item Descriptions and put the selected item in the newly created LineOnPickList record when Create was clicked.
What I need to do however is show a dropdownlist of Location BinNumbers, yet still have the Item associated with that Location in the newly created LineOnPickList record.
How would that be done?
Define a view model for your drop down
public class ItemViewModel
{
public int ID { get; set; }
public string BinNumber { get; set; }
}
Then build the drop down list data in your controller action as follows
public class CreateLineOnPickListViewModel
{
public int ItemId { get; set; }
public IEnumerable<ItemViewModel> Items { get; set; }
}
public ActionResult Create()
{
var model = new CreateLineOnPickListViewModel();
model.Items = db.Items
.Select(i => new ItemViewModel { ID = i.ID, BinNumber = i.Bin.BinNumber });
return View(model);
}
Then in your view
#model CreateLineOnPickListViewModel
#Html.DropDownListFor(m => m.ItemId, new SelectList(Model.Items, "ID", "BinNumber"), "-")
Then your post action method in your controller would look like this
public ActionResult Create(CreateLineOnPickListViewModel model)
{
var item = new Item { ID = model.ItemID };
db.Items.Attach(item);
var lineOnPickList = new LineOnPickList { Item = item };
db.SaveChanges();
return View(model);
}

MVC-Viewmodel and LINQ, Insert value into a table and the value gets tagged by two other values in two other tables

I am using MVC-Viewmodel with repository pattern with EF on my project.
I have 3 tables, Question, CoreValue, SubjectType.
SubjectType and CoreValue are many to many associated with Question and these two tables are not suppose to get any new values, but users can create questions so Question table will get new data when a user creates it. I use two dropdownlists for CoreValue and SubjectType so that the user can choose a CoreValue and a SubjectType when they create a Question.
Here is my HTTPGET controller action:
// GET: /Admin/Create
public ActionResult Create()
{
CoreValueRepository Crep = new CoreValueRepository();
SubjectTypeRepository Srep = new SubjectTypeRepository();
CreateViewModel model = new CreateViewModel();
List<SubjectType> subjectypes = Srep.getall();
List<CoreValue> corevalues = Crep.getall();
model.SubjectTypes = new SelectList(subjectypes, "SID", "Sname");
model.CoreValues = new SelectList(corevalues, "CID", "Cname");
return View(model);
}
And here is my Viewmodel:
public class CreateViewModel
{
public string QuestionText { get; set; }
public string Sname { get; set; }
public string Cname { get; set; }
public SelectList SubjectTypes { get; set; }
public SelectList CoreValues { get; set; }
}
I use Repository for CRUD operations and viewmodels for handling data in UI.
Now I have to code the HTTPPOST Action Create in my controller for inserting Question data to my database, and the questions need to be tagged with CoreValue ID and SubjectType ID. So I was thinkin about to start coding the HTTPOST action Create, and I was wondering if someone could help me out with this.
Thanks in advance!
Best Regards!
This is how i would handle it :
In your ViewModel, replace :
public class CreateViewModel {
public string QuestionText { get; set; }
public string Sname { get; set; }
public string Cname { get; set; }
public int SubjectTypesID { get; set; }
public int CoreValuesID { get; set; }
}
In your HTTPGET put your list in Viewbags :
public ActionResult Create()
{
CoreValueRepository Crep = new CoreValueRepository();
SubjectTypeRepository Srep = new SubjectTypeRepository();
CreateViewModel model = new CreateViewModel();
ViewBag.SubjectTypes = Srep.getall();
ViewBag.CoreValues = Crep.getall();
return View(model);
}
To use the viewbag in your view you can use this :
#Html.DropDownList("SubjectTypesID ", new SelectList(ViewBag.SubjectTypes as System.Collections.IEnumerable, "SID", "Sname", Model.SubjectTypesID ))
#Html.DropDownList("CoreValuesID ", new SelectList(ViewBag.CoreValues as System.Collections.IEnumerable, "CID", "Cname", Model.CoreValuesID ))
Your HTTPOST :
[HTTPOST]
public ActionResult Create(CreateViewModel model)
{
//Now with your model you have the Id of CoreValue and SubjectType
//You could do
if (ModelState.IsValid)
{
QuestionRep.Add(model);
return RedirectToAction("Index");
}
return View(model);
}
Hope this can help you :)
Edit :
in my repository I do :
public void Add(Model.Models.LabExam.Examen entity)
{
using (var context = new PDSIDataContext())
{
var exam = BindModelExamenToRepExamen(entity);
context.Examen.InsertOnSubmit(exam);
context.SubmitChanges();
}
}
Binding methods (Repository.Examen represents my table, Repository is my project where I have a .dbml to represent my DB):
private static Repository.Examen BindModelExamenToRepExamen(Model.Models.LabExam.Examen modelExamen)
{
return new Repository.Examen
{
ID_Examen = modelExamen.ID,
ID_Examen_Type = modelExamen.ID_Examen_Type,
Date_Prescription = modelExamen.Date_Prescription,
Realise_Le = modelExamen.Realise_Le,
Statut = modelExamen.Statut,
Fait = modelExamen.Fait,
ID_Examen_Sous_Type = modelExamen.ID_Examen_Sous_Type,
ID_Examen_Sous_Sous_Type = modelExamen.ID_Examen_Sous_Sous_Type,
ID_Patient = modelExamen.ID_Patient,
Commentaires = modelExamen.Commentaires
};
}

Resources