I am new to Struts 2 framework. I have made a program for understanding modelDriven interceptor. But I am unable to execute it. Following are the list of files and in the end there is a output (error).
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%-- <jsp:useBean id="ent" class="pack.Entity" scope="session" /> --%>
<s:form method="get" action="go">
<s:textfield name="t1" label="Name"></s:textfield>
<s:password name="p1" label="Password"></s:password>
<s:submit value="accept"></s:submit>
</s:form>
</body>
</html>
Entity.java:
package actions_pack;
public class Entity {
private String t1;
private String p1;
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
public Entity() {
super();
// TODO Auto-generated constructor stub
}
public String getT1() {
return t1;
}
public void setT1(String t1) {
this.t1 = t1;
}
}
GoAction.java:
package actions_pack;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor;
import com.opensymphony.xwork2.util.ValueStack;
public class GoAction implements ModelDriven<Entity> {
private Entity en;
public Entity getEn() {
return en;
}
public void setEn(Entity en) {
this.en = en;
}
public String execute(){
System.out.println("inside action");
if(en.getT1().equalsIgnoreCase("nitin")){
return "success";
}
else{
return "failure";
}
}
#Override
public Entity getModel() {
System.out.println("inside model driven....");
en=new Entity();
return en;
}
}
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="dd">
<result-types>
<result-type name="dispatcher"
class="org.apache.struts2.dispatcher.ServletDispatcherResult"
default="true" />
</result-types>
<interceptors>
<interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
<interceptor-stack name="myStack">
<interceptor-ref name="modelDriven"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="go" class="actions_pack.GoAction">
<interceptor-ref name="myStack"></interceptor-ref>
<result name="success" type="dispatcher" >/one/welcome.jsp</result>
<result name="failure" type="dispatcher">/one/error.jsp</result>
</action>
</package>
</struts>
welcome.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Welcome, <s:property value="t1"/>
</body>
</html>
web-page output(500 error):
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
actions_pack.GoAction.execute(GoAction.java:24)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.
Apache Tomcat/7.0.34
In struts.xml file I don't want to use/extend struts-default package. Although, when I include params interceptor entry along with modelDriven interceptor in struts.xml, problem solves. What is the reason behind this. Can any one guide me?
You have a property in the action class that needs initialize prior to the action execution. You can do it in many ways.
The way you have chosen relies on modelDriven interceptor which is running before your action is executed. It invokes getModel() to push it on top of the valueStack. So, your entity property is being initialized. If you remove this interceptor you will get NullPointerException when the action is executed.
If your Entity is a simple POJO that you can instantiate yourself then simply do it inline instead of in getModel().
private Entity en = new Entity();
#Override
public Entity getModel() {
System.out.println("inside model driven....");
return en;
}
Next part is about params interceptor. It uses OGNL to populate a top object that is a model if you have used modelDriven interceptor prior params interceptor.
Living it along with your action allows to initialize some properties you reference in the execute().
For example t1 should be initialized.
Im trying tot start with a easy setup. I try to get de data into textboxes and start with the first step. For some reason I can't bind the data to the textbox and don't received any errors. Programming is running fine, but nothing is happening when I press the button.
I tested with gridview to check the connection and that seems to be working.
I'm using MS SQL Server 2016 Express version, visual studio 2017, ASP and C#
What do I wrong? Wrong code? Connection blocked by the server?
.........................
ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test3.aspx.cs" Inherits="test3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Width="281px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Start" />
</div>
</form>
</body>
</html>
.............................
The CS code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class test3 : System.Web.UI.Page
{
public SqlConnection conn = new SqlConnection(#"Data Source=.\WDVEXPRESS;Initial Catalog=user;User ID=testaccount;Password=123test");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand com;
string str;
conn.Open();
str = "select * from Company$ where Name = 'testuser'";
com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
TextBox1.Text = reader["Name"].ToString();
reader.Close();
conn.Close();
}
}
}
.......................
Many thanks for the help!
Your button on aspx page is not bound to button click event on aspx.cs page. Check below code it will tell you how they got bounded -
HTML ( ASPX PAGE ) CODE
<asp:Button ID="Button1" runat="server" Text="Start" OnClick="Button1_Click" />
CS CODE
protected void Button1_Click(object sender, EventArgs e)
{
//Your Click Event Here
}
I have:
VS 2013
MVC 5.2.2
Razor 3.2.2
Let me know if there's anything else you need to know.
This problem only happens on one view page.
I have a View with all HTML tags closed off properly
It's your standard view...
#model MyNameSpace.Models.Inquiry
#{
var hasFormSetup = Model != null && Model.FormSetup != null && Model.FormSetup.Count > 0;
if (hasFormSetup)
{
ViewBag.Title = Model.FormSetup[0].InquiryValue;
}
Layout = "~/Views/Shared/_LayoutInquiry.cshtml";
}
<style scoped>
ul {
list-style-type: none;
}
</style>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="container" style="margin-top: 5px;">
etc...
</div>
<div class="container" >
etc...
</div>
}
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
etc...
});
</script>
}
but...
on the line
#section Scripts
Resharper reports: "Cannot resolve section Scripts"
When I run, I get the exception:
Source: System.Web.WebPages
Target: Void VerifyRenderedBodyOrSections()
Type: HttpException
Message: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_LayoutInquiry.cshtml": "Scripts".
Stack: at System.Web.WebPages.WebPageBase.VerifyRenderedBodyOrSections()
at System.Web.WebPages.WebPageBase.PopContext()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.WebPages.WebPageBase.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer)
at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
at System.Web.WebPages.WebPageBase.Write(HelperResult result)
at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body)
at System.Web.WebPages.WebPageBase.PopContext()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
etc...
No other page has this issue.
Any ideas as to how I can fix this?
The exception message says:
The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_LayoutInquiry.cshtml": "Scripts".
This suggests that your _LayoutInquiry.cshtml page does not setup a placeholder for a Scripts section. You can do this by adding #RenderSection("Scripts", false) to your layout page in the appropriate location, where the false indicates that views may optionally supply this section.
Now, when your view renders, the contents of #section Scripts { ... } in your view will be rendered into the location of the #RenderSection("Scripts", false) call in your layout page.
I had this same issue but using Rider instead of VS. The code was actually legit, but some cache got in the way.
So the solution was to "Invalidate and Restart" - found in File > Invalidate caches...
For others that may end up here. Everything is working OK but ReSharper complains about Section and Styles missing.
Our case was that we had _Layout.cshtml and _Layout.Mobile.cshtml in the shared folder.
Having an issue with an MVC 2.0 application partial view that all of the sudden when accessed and stuff is actually in the ViewData, the dreaded No parameterless Constructor error. I Have followed the code as much as I can and I'm getting no where. Here is my code:
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using CINet.Areas.CatalystSearch.Models.Interfaces;
using CINet.Areas.CatalystSearch.Models.Repository;
using CINet.Areas.CatalystSearch.Models.Entities;
namespace CINet.Areas.CatalystSearch.Controllers
{
public class CatalystSearchController : Controller
{
// private SqlCatalystRepository _catalystItemRepository;
private ICatalystRepository _catalystInterface;
public int PageSize = 10; // Regulates size of page
#region CONSTRUCTOR
/// <summary>
/// Constructor which sets the passed repository to the local current
/// repository
/// </summary>
/// <param name="catalystRepository">Interface repository for controller</param>
public CatalystSearchController()
{
}
#endregion
#region DEFAULT VIEW
public ViewResult List([DefaultValue("")] string manufactureName, [DefaultValue("")] string manufacturePartNumber, [DefaultValue("")] string description, [DefaultValue(1)] int page)
{
IQueryable<CatalystItem> query = null;
CatalystFilter userFilter = new CatalystFilter();
int totalItems = 0;
// Be sure that the manufacture drop down has been selected
if (manufactureName != "")
{
// Set up CatalystFilter
userFilter.Manufacture = manufactureName;
userFilter.DescriptionFilter = description;
userFilter.ManufacturePartNumberFilter = manufacturePartNumber;
// connection string for SQL
string connString = "Data Source=se-cinet-dev;Initial Catalog=cinet;User ID=sa;Password=Carouse1";
// Get interface
_catalystInterface = new CatalystRepository(connString);
// Collects data from SQL repository and updates private local copy
// _catalystItemRepository = new SqlCatalystRepository(connString);
// Fills with list of Catalystitems based on filter.
query = _catalystInterface.GetCatalystItems(userFilter, page, PageSize);
// query = _catalystItemRepository.GetItems(userFilter, page, PageSize);
// Returns int of total items in list
totalItems = _catalystInterface.GetTotalOfItems(userFilter);
// totalItems = _catalystItemRepository.GetTotalOfItems(userFilter);
// Set up view model for passing to View
var viewModel = new CatalystModel
{
catalystItems = query.ToList(),
catalystFilter = userFilter,
/* Pass Paging properties to model*/
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = totalItems
},
ManufactureName = manufactureName
};
// View Data to be passed to SearchView
ViewData["catalystItems"] = viewModel;
return View(viewModel);
}
else
{
var viewModel = new CatalystModel();
return View(viewModel);
}
}
#endregion
#region SEARCH VIEW
/// <summary>
/// Partial View used to display results from controller
/// </summary>
/// <param name="model"> model passed via ViewData from List View</param>
/// <returns></returns>
[ChildActionOnly]
public ViewResult SearchView(CatalystModel model)
{
return View(model);
}
#endregion
}
}
listView:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CINet.Areas.CatalystSearch.Models.Entities.CatalystModel>" %>
<%# Import Namespace="CINet.Areas.CatalystSearch.HtmlHelpers" %>
<%# Import Namespace="CINet.Areas.CatalystSearch.Models" %>
<%# Import Namespace="CINet.Areas.CatalystSearch.Models.Interfaces" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div>
<center>
<strong>
<%= Html.ValidationSummary("Please fill out required Fields") %></strong>
<h1>Catalyst Search Provider</h1>
<hr />
<%-- "Search","Catalyst" --%>
<%
using (Html.BeginForm())
{ %>
<table border="1">
<tr>
<td>Enter Description (optional):</td>
<td>
<%: Html.TextBoxFor(x=>x.Description) %>
</td>
</tr>
<tr>
<td>Enter Part Number (optional):</td>
<td>
<%: Html.TextBoxFor(x=>x.ManufacturePartNumber) %>
</td>
</tr>
<tr>
<td>Choose Manufacture:
</td>
<td>
<%: Html.DropDownListFor(x => x.ManufactureName, Model.GetAllManufactures()) %>
<%-- <%: Html.DropDownList("ManufactureName", Model.GetAllManufactures(),"Choose Item")%> --%>
</td>
</tr>
<tr>
<td>
 
</td>
<td>
<input type="submit" name="Search" value="Search" />
</td>
</tr>
</table>
<% } Html.EndForm(); %>
<!-- RENDERS PARTIAL VIEW TO DISPLAY GRID WITH SEARCH RESULTS -->
<% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
<br />
</center>
</div>
<div class="pager">
<% if (Model.PagingInfo != null)
{ %>
<%: Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, manufactureName = Model.catalystFilter.Manufacture, description = Model.catalystFilter.DescriptionFilter, manufacturePartNumber = Model.catalystFilter.ManufacturePartNumberFilter }))%>
<% } %>
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
</asp:Content>
SearchView:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CINet.Areas.CatalystSearch.Models.Entities.CatalystModel>" %>
<%# Import Namespace="CINet.Areas.CatalystSearch.HtmlHelpers" %>
<%# Import Namespace="CINet.Areas.CatalystSearch.Models" %>
<div>
<% if (Model.catalystItems != null)
{ %>
<table class="CatalystTableSpacer">
<tr>
<td>
Contract Price
</td>
<td>
Description
</td>
<td>
Manufacture Name
</td>
<td>
Manufacture Part Number
</td>
<td>
MSRP Price
</td>
<td>
Quantity Available
</td>
</tr>
<% foreach (var items in Model.catalystItems)
{%>
<tr>
<td>
<%: items.ContractPrice%>
</td>
<td>
<%: items.Description%>
</td>
<td>
<%: items.ManufactureName%>
</td>
<td>
<%: items.ManufacturePartNumber%>
</td>
<td>
<%: items.MSRPrice%>
</td>
<td>
<%: items.QuantityAvailable%>
</td>
</tr>
<% }
}
%>
</table>
</div>
CatalystModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CINet.Areas.CatalystSearch.Models.Entities;
using System.ComponentModel.DataAnnotations;
using CINet.Areas.CatalystSearch.Models.Repository;
using CINet.Areas.CatalystSearch.Models.Interfaces;
namespace CINet.Areas.CatalystSearch.Models.Entities
{
public class CatalystModel
{
#region PRIVATE FIELDS
private string _connectionString = "Data Source=se-cinet-dev;Initial Catalog=cinet;User ID=sa;Password=Carouse1"; // connection string for SQL
private ICatalystRepository _repository = null;
#endregion
#region PUBLIC PROPERTIES
public IList<CatalystItem> catalystItems { get; set; }
public PagingInfo PagingInfo { get; set; }
public CatalystFilter catalystFilter { get; set; }
public SelectList Manufactures { get; set; }
public SelectList Categories { get; set; }
[Required]
public string ManufactureName { get; set; }
public string Description { get; set; }
public string ManufacturePartNumber { get; set; }
#endregion
#region CONSTRUCTOR
/// <summary>
/// Constructor instantiates SQL DB Connection
/// </summary>
public CatalystModel()
{
_repository = new CatalystRepository(_connectionString);
// Manufactures = GetAllManufactures();
}
#endregion
#region PUBLIC GET LISTS
/// <summary>
/// Returns ALL Manufactures in Database
/// </summary>
/// <returns></returns>
public SelectList GetAllManufactures()
{
SelectList manufactureNameSelectList;
List<Manufacture> manufactureTempList = new List<Manufacture>();
// Get List from DB
manufactureTempList = _repository.GetManufactureList();
// PUSH LIST INTO SELECT LIST
manufactureNameSelectList = new SelectList(manufactureTempList, "ManufactureName", "ManufactureName");
return manufactureNameSelectList;
}
#endregion
}
}
The error happens in the ListView calling the SearchView:
<% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
Any help??
Actual Error:
Server Error in '/' Application.
--------------------------------------------------------------------------------
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
Line 53: <!-- RENDERS PARTIAL VIEW TO DISPLAY GRID WITH SEARCH RESULTS -->
Line 54: <%-- <% Html.RenderPartial("SearchView", ViewData["catalystItems"]); %>
Line 55: --%> <% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
Line 56:
Line 57: <br />
Source File: c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Areas\CatalystSearch\Views\CatalystSearch\List.aspx Line: 55
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +403
System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +544
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +479
System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +658
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +475
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +44
System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +34
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +76
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +113
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +124
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1072
[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3058371
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +77
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +22
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +766
System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +98
System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, Object routeValues) +65
ASP.areas_catalystsearch_views_catalystsearch_list_aspx.__RenderContent1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Areas\CatalystSearch\Views\CatalystSearch\List.aspx:55
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
ASP.views_shared_site_master.__Renderform1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\gcoleman\Documents\Source Code\Sandbox\Jonathan Henk\MVC\CINet\CINet\Views\Shared\Site.Master:26
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +8820669
System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +31
System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +53
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Page.Render(HtmlTextWriter writer) +29
System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +56
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237
Your problem is that the CatalystModel class doesn't have a default constructor so the default model binder cannot instantiate it here:
[ChildActionOnly]
public ViewResult SearchView(CatalystModel model)
{
return View(model);
}
This being said having such a child controller action that you are invoking like this:
<% Html.RenderAction("SearchView", ViewData["catalystItems"]); %>
is totally useless and bring strictly no value.
Why don't you render the partial directly:
<% Html.RenderPartial("SearchView", ViewData["catalystItems"]); %>
You should also read the Haacked blog post to better understand the differences between RenderAction and RenderPartial.
Or if you really (for some cryptic reason) have controller actions that take some models which do not have default constructors as action parameters you will need to write a custom model binder for this type and specify which of your custom constructors should be used to instantiate it and what values should be passed to it of course.
Try this:
<% Html.RenderAction("SearchView", new { model = ViewData["catalystItems"] }); %>
I have translated Jeremiah Clark's CheckBoxList Helper for MVC into my VB.Net project but when I try to use the method in my view I get the error
'CheckBoxList' is not a member of 'System.Web.Mvc.HtmlHelper(Of Attenda.Stargate.Web.UserRolesViewModel)'.
Can anyone tell me where I have gone wrong?
Helper module:
Imports System.Runtime.CompilerServices
Public Module InputExtensions
<Extension()> _
Public Function CheckBoxList(ByVal htmlHelper As HtmlHelper, ByVal name As String, ByVal listInfo As List(Of ListItem)) As String
Return htmlHelper.CheckBoxList(name, listInfo, DirectCast(Nothing, IDictionary(Of String, Object)))
End Function
<Extension()> _
Public Function CheckBoxList(ByVal htmlHelper As HtmlHelper, ByVal name As String, ByVal listInfo As List(Of ListItem), ByVal htmlAttributes As Object) As String
Return htmlHelper.CheckBoxList(name, listInfo, DirectCast(New RouteValueDictionary(htmlAttributes), IDictionary(Of String, Object)))
End Function
<Extension()> _
Public Function CheckBoxList(ByVal htmlHelper As HtmlHelper, ByVal name As String, ByVal listInfo As List(Of ListItem), ByVal htmlAttributes As IDictionary(Of String, Object)) As String
If String.IsNullOrEmpty(name) Then
Throw New ArgumentException("The argument must have a value", "name")
End If
If listInfo Is Nothing Then
Throw New ArgumentNullException("listInfo")
End If
If listInfo.Count < 1 Then
Throw New ArgumentException("The list must contain at least one value", "listInfo")
End If
Dim sb As New StringBuilder()
For Each info As ListItem In listInfo
Dim builder As New TagBuilder("input")
If info.Selected Then
builder.MergeAttribute("checked", "checked")
End If
builder.MergeAttributes(Of String, Object)(htmlAttributes)
builder.MergeAttribute("type", "checkbox")
builder.MergeAttribute("value", info.Value)
builder.MergeAttribute("name", name)
builder.InnerHtml = info.Text
sb.Append(builder.ToString(TagRenderMode.Normal))
sb.Append("<br />")
Next
Return sb.ToString()
End Function
End Module
View source:
<%# Page Title="" Language="VB" MasterPageFile="~/Views/Shared/TwoColumn.Master" Inherits="System.Web.Mvc.ViewPage(Of Attenda.Stargate.Web.UserRolesViewModel)" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit User Roles
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit Roles for
<%=Html.Encode(Model.User.UserName)%></h2>
<div>
<%=Html.CheckBoxList("Roles", Model.Roles)%>
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphLeftPanel" runat="server">
</asp:Content>
You need to import the namespace containing the custom helper class into your view page. You can do this on the page itself or in the web.config file for all pages. Put the code into a namespace first.
<%# Import Namespace="MyProject.Extensions" %>
or (in the web.config)
<pages>
...
<namespaces>
...
<add namespace="MyProject.Extensions" />
</namespaces>
</pages>
I encountered this problem because I hadn't declared the Module to be Public.
This question also asked here