MVC3 error when trying to render action as partial view - asp.net-mvc

I'm getting the following error when trying to use Html.Action to render a page as a partial view:
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper
View code:
#Html.Action("Index", "Location", new { userId = 3428 })
Controller code:
public class Location : Controller
{
private void PopulateDropdowns(LocationViewModel model, int userId)
{
var lookup = new AWS.BL.Lookup();
model.Areas = lookup.GetAreas(userId);
model.SEATs = new List<DTO.Lookup>();
model.Establishments = new List<DTO.Lookup>();
model.Properties = new List<DTO.Lookup>();
}
public ActionResult Index(int userId)
{
var model = new LocationViewModel();
PopulateDropdowns(model, userId);
return PartialView(model);
}
}
Any help greatly appreciated.

Related

Display ads on multiple Views by using single controller method in MVC

I want to display different ads on multiple Views from single method. Currently, I have created separate controller method for the ads and then passing page name by using session from each View's controller method. I want to get rid off any code related to ads from each controller method.
Please suggest me way to do this.
Home controller
public ActionResult Index()
{
ClsHomeContent model = new ClsHomeContent();
List<Advertisement> advertList = new List<Advertisement>();
var context = new ApplicationDbContext();
var advert = context.Advertisement.ToList();
var pageName = context.Advertisement.Where(x => x.Page == "Home").Select(y => y.Page).FirstOrDefault();
Session["PageName"] = pageName;
return View(model);
}
HorseTracker Controller
public ActionResult HorseTracker()
{
List<Advertisement> advertList = new List<Advertisement>();
var advert = context.Advertisement.ToList();
var pageName = context.Advertisement.Where(x => x.Page == "HorseTracker").Select(y => y.Page).FirstOrDefault();
Session["PageName"] = pageName;
return View(model);
}
Then using this session value
public ClsAdvertisment advertPosition()
{
List<Advertisement> advertList = new List<Advertisement>();
ClsAdvertisment model = new ClsAdvertisment();
var context = new ApplicationDbContext();
var advert = context.Advertisement.ToList();
foreach (var advertisementData in advert)
{
if (advertisementData.Position == Session["PageName"] + "_Top_Left" || advertisementData.Position == Session["PageName"] + "_Top_Right" || advertisementData.Position == Session["PageName"] + "_Middle" || advertisementData.Position == Session["PageName"] + "_Left")
{
advertList.Add(new Advertisement()
{
AdvertId = advertisementData.AdvertId,
Position = advertisementData.Position,
FilePath = advertisementData.FilePath,
Hemisphere = advertisementData.Hemisphere,
Link = advertisementData.Link,
Title = advertisementData.Title
});
}
}
model.advertisement = advertList;
return model;
}
[ChildActionOnly]
public PartialViewResult Advertisement()
{
var model= advertPosition();
return PartialView("_pAdvertisement", model);
}
Created separate partial view
foreach (var item in Model.advertisement)
{
if (#item.Hemisphere == 1 && item.Position == (string)Session["PageName"]+"_Top_Left")
{
<a href="#item.Link" title="#item.Title" target="_blank">
#Html.Image(item.FilePath, "Image", "", "")
</a>
}
}
You can get the name of the parent controller and action methods in the child method using the ParentActionViewContext property of ControllerContext
[ChildActionOnly]
public PartialViewResult Advertisement()
{
ViewContext context = ControllerContext.ParentActionViewContext;
string controllerName = context.RouteData.Values["controller"].ToString();
string actionName = context.RouteData.Values["action"].ToString();
ClsAdvertisment model = advertPosition(controllerName, actionName);
return PartialView("_pAdvertisement", model);
}
Then modify your advertPosition() to
public ClsAdvertisment advertPosition(string controllerName, string actionName)
and within that method, select the ads to be displayed based on those values, and there is also no need to use Session.

Unit testing controller action which redirects to another action

I am following TDD approach to develop my MVC website. I have a PaymentController which is going to have an action method MakePayment which I am testing using a test method as given below:
[TestMethod]
public void MakePaymentLoad()
{
PaymentController payController = new PaymentController();
ViewResult payResult = payController.MakePayment() as ViewResult;
Assert.IsNotNull(payResult);
}
[TestMethod]
public void MakePaymentResult()
{
PaymentController payController = new PaymentController();
Payment payment = new Payment {
BillerId = 1,
PayAmt = 1.0,
PayDt = DateTime.Now,
ConfCode = null,
BillAccount = "123",
PayStatus = 1,
FeeStatus = 1,
Platform =1
};
ViewResult payResult = payController.MakePayment(payment) as ViewResult;
PaymentResult result = payResult.Model as PaymentResult;
Assert.IsNotNull(result.ConfCode);
}
In the above given test methods MakePaymentLoad only checks if the view is rendered and MakePaymentResult checks out if the confirmation code is present in the view model.
My action methods are given below:
[HttpPost]
public ActionResult MakePayment(Payment payment)
{
PaymentResult payResult = new PaymentResult {
ConfCode = "123"
};
if (true)
{
TempData["ConfCode"] = "123";
return RedirectToAction("Confirmation");
}
return View(payment);
}
public ViewResult MakePayment()
{
return View();
}
public ActionResult Confirmation()
{
PaymentResult result = new PaymentResult {
ConfCode = Convert.ToString(TempData["ConfCode"])
};
return View(result);
}
The MakePaymentLoad passes as it only check if the view is rendered whereas MakePaymentResult fails miserably as the result of action method is null because of the use RedirectToAcion inside MakePayment's post version. Please let me know how to fix this.
you should test it like following
var payResult = (RedirectToActionResult)payController.MakePayment(payment)
Assert.AreEqual("Confirmation", action.RouteValues["action"]);
As you are returning redirect result, you can't expect a model in return.

Returning single item in model - mvc razor

I have a finalist page that displays a list of finalists, that are clickable into a single-view page. I have the XML document being passed into a model and am spilling that data onto the main finalists page, but I can't seem to figure out how to grab the clicked finalist's id and display only that finalist on the single-view page.
Any help is appreciated, here is my controller right now:
I am trying to pass the newly created model in to the singleView class, but I'm not sure how to filter it to know which finalist was clicked on, and which finalist to display on the single-view page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using ProjectX_Awards.Models;
namespace ProjectX_Awards.Controllers
{
public class FinalistsController : Controller
{
//
// GET: /Finalists/
public ActionResult Index()
{
var doc = XElement.Load(HttpContext.Server.MapPath("~/finalist.xml"));
var finalists = doc.Descendants("finalist").Select(f => new Models.Finalist()
{
Id = (int)f.Attribute("id"),
Name = f.Descendants("name").First().Value,
Description = f.Descendants("description").First().Value,
Link = f.Descendants("webLink").First().Value,
Photo = f.Descendants("photoUrl").First().Value
});
return View(finalists);
}
public ActionResult SingleView(Finalist model)
{
var singleFinalist = model;
return View(singleFinalist);
}
}
}
If you want to pass a complete model, you need to do a POST to that action-method. The easiest way is to make sure you post all the values in a form-element to the specified action. However, the best thing would be to pass an Id to your SingleView-method. This allows you to do a get to that page, instead of having to post a complete object:
public ActionResult SingleView(int id)
{
var singleFinalist = model;
var doc = XElement.Load(HttpContext.Server.MapPath("~/finalist.xml"));
var finalist = doc.Descendants("finalist").Where(f => (int)f.Attribute("id") == id)
.Select(f => new Models.Finalist()
{
Id = (int)f.Attribute("id"),
Name = f.Descendants("name").First().Value,
Description = f.Descendants("description").First().Value,
Link = f.Descendants("webLink").First().Value,
Photo = f.Descendants("photoUrl").First().Value
})
.FirstOrDefault;
return View(finalist);
}
Then in your finalists-page you can just emit an a-tag like this:
#foreach(var finalist in Model)
{
Detail
// or
#Html.ActionLink("SingleView", "YourController", new { id = finalist.id })
}
EDIT Adding a simple caching method, so the XML is not reloaded everytime:
public ActionResult Index()
{
return View(GetAllFinalists());
}
public ActionResult SingleView(int id)
{
var doc = XElement.Load(HttpContext.Server.MapPath("~/finalist.xml"));
var finalist = GetAllFinalists().Where(f => f.Id == id)
.FirstOrDefault;
return View(finalist);
}
private IEnumerable<Models.Finalist> GetAllFinalists()
{
if (HttpContext.Current.Application["finalists"] == null)
{
var doc = XElement.Load(HttpContext.Server.MapPath("~/finalist.xml"));
HttpContext.Current.Application["finalists"] = doc.Descendants("finalist")
.Select(f => new Models.Finalist()
{
Id = (int)f.Attribute("id"),
Name = f.Descendants("name").First().Value,
Description = f.Descendants("description").First().Value,
Link = f.Descendants("webLink").First().Value,
Photo = f.Descendants("photoUrl").First().Value
});
}
return (IEnumerable<Models.Finalist>)HttpContext.Current.Application["finalists"];
}

Getting Error While Using ActionResult

I have a View(FilerOverall) and inside the view i am calling some method using renderaction method.
#{
Html.RenderAction("Gettemplate", "FinancialDisclosure",
new { FormId = "100",ScheduleId= "10" });
};
and in controller i have written the action method like
public ActionResult Gettemplate(string FormId ,string ScheduleId)
{
List<FDDTO> FD1 = FDService.GetScheduleDetails(100, 10).ToList();
return View ("EditorTemplates/FDDTO", FD1);
}
when I executed the app I am getting this error:
"A public action method 'Gettemplate' was not found on controller
'WorldBank.DOI.Presentation.Controllers.FinancialDisclosureController'."}
Try #Html.Action instead of Html.RenderAction
#Html.Action("Gettemplate", "FinancialDisclosure", new { FormId = "100",ScheduleId= "10" })
you should try this
Create new view like Demo.cshtml
now
public ActionResult Gettemplate(string FormId ,string ScheduleId)
{
List<FDDTO> FD1 = FDService.GetScheduleDetails(100, 10).ToList();
return View ("Demo", FD1);
}
now put in your FilerOverall.cshtml below code
#{
Html.RenderAction("Gettemplate", "FinancialDisclosure",
new { FormId = "100",ScheduleId= "10" });
};

View doesn't refresh after RedirectToAction is done

Here is my problem:
[HttpPost]
public ActionResult AddData(CandidateViewModel viewModel)
{
var newCandidateId = 0;
newCandidateId = this._serviceClient.AddCandidate(viewModel);
return RedirectToAction("DisplayCandidate",new {id=newCandidateId});
}
public ActionResult DisplayCandidate(int id)
{
var candidateViewModel= this._serviceClient.GetCandidate(id);
return View(candidateViewModel);
}
After filling the form viwemodel sends to server. After data were stored, flow is redirected to DisplayCandidate action and it goes there but page didn't refresh. I don't understand why! Help, please.
Because you are using Ajax Post
public ActionResult AddData(CandidateViewModel viewModel)
{
var newCandidateId = 0;
newCandidateId = this._serviceClient.AddCandidate(viewModel);
string ReturnURL = "/DisplayCandidate/"+newCandidateId;
return JSON(ReturnURL);
}
and in your Ajax Post Method:
Onsuccess(function(retURL){ window.location(retURL); })
This will take to the new Action and that Action will return View.
If you're using Ajax, return a script results to execute the navigation
instead of
return RedirectToAction("DisplayCandidate",new {id=newCandidateId});
try
var viewName = "/Path/ViewName";
var id = 1;
var urlNavigate = string.Format("location.href='{0}?id={1}'", viewName, id);
return new JavaScriptResult() { Script = urlNavigate };

Resources