Can't use codeblock in control property - c#

The abstract problem: I'm trying to limit user input in text fields to the same as the database length of the column. So I want to set a maxlength attribute on an html input, and the maxlength should be the same as the max length allowed in the database. I could hardcode these constants throughout the frontend, but I'm trying to set that value dynamically.
The problem: telerik RadComboBox won't accept an asp code block to set a property. The exception is as follows:
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Cannot create an object of type 'System.Int32' from its string representation '<% Utility.GetColumnMaxLength<Portfolio>(x => x.Title) %>' for the 'MaxLength' property.
I've created a new minimal asp.net project to duplicate the problem. default.aspx source (no .cs code behind):
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TelerikCodeBlock._Default" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%# Import namespace="TelerikCodeBlock" %>
<%# Import namespace="TelerikCodeBlock.DataModel" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<telerik:RadComboBox ID="txtboxTitle" runat="server" MaxLength="<% Utility.GetColumnMaxLength<Portfolio>(x => x.Title) %>" >
</telerik:RadComboBox>
</asp:Content>
The Utility class has been minimized to the following
namespace TelerikCodeBlock
{
public class Utility
{
public static int GetColumnMaxLength<T>(Expression<Func<T, object>> property)
{
// looks at Entity Framework metadata in real project ...
return 3;
}
}
}
Data model looks like
namespace TelerikCodeBlock.DataModel
{
public class Portfolio
{
public int Id { get; set; }
public string Title { get; set; }
}
}

Possible workaround: using ASP.NET Expressions (the <%$ ... %> code blocks), build a general expression that executes code, as outlined here.
Add a reference to Microsoft.CodeDom.Providers.DotNetCompilerPlatform.
Define the following somewhere:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
namespace TelerikCodeBlock
{
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
}
And register it in the web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" >
<expressionBuilders>
<add expressionPrefix="Code" type="TelerikCodeBlock.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
...
Now change the asp control to use the expression code block:
<telerik:RadComboBox ID="txtboxTitle" runat="server" MaxLength="<%$ Code: Utility.GetColumnMaxLength<Portfolio>(x => x.Title) %>" >

Related

Asp.net MVC 4 and SolrNet programing

to all, I realy need help. I am new in SolrNet and beginer in asp.net mvc 4. My project is to use SolrNet and view results in web app created in asp.net mvc 4. So, for begin I whant to just do simple query from SolrNet and display it in web,
So far I have create this:
Start new empty MVC project with name: SOLRTest
From Package Manager Console I have done this: Instal-Package SolrNet -Version 0.4.0-beta2
In HomeController i use this code:
using System;
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
using SOLRTest.Models;
using SolrNet;
namespace SOLRTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
try
{
var solr = ServiceLocator.Current.GetInstance<ISolrReadOnlyOperations<Customer>>();
SolrQueryResults<Customer> rezultati = solr.Query(new SolrQueryByField("customer", "INTS"));
return RedirectToAction("Index", "Home");
}
catch (Exception ex)
{
string error = ex.Message;
}
return View();
}
}
}
In Models i use this code:
using SolrNet.Attributes;
namespace SOLRTest.Models
{
public class Customer
{
[SolrField("customer")]
public string customer { get; set; }
}
}
In View i use this code:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<%# Import Namespace="SOLRTest.Helpers" %>
<%# Import namespace="SOLRTest.Models" %>
<!DOCTYPE html>
<html>
<body>
<div>
test
</div>
</body>
</html>
<% foreach (var izpis in SOLRTest.Models.Customer)
{ %>
<li>
<ul>
<%= Html.SolrFieldPropName<Customer>(izpis) %>
</ul>
</li>
<% } %>
For Helpers I use this code:
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
using SolrNet;
namespace SOLRTest.Helpers
{
public static class HtmlHelperMapperExtensions
{
private static IReadOnlyMappingManager mapper
{
get { return ServiceLocator.Current.GetInstance<IReadOnlyMappingManager>(); }
}
public static string SolrFieldPropName<T>(this HtmlHelper helper, string fieldName)
{
return mapper.GetFields(typeof(T))[fieldName].Property.Name;
}
}
}
And finaly in Global.asax I use this to connect to server:
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using SOLRTest.Models;
using SolrNet;
namespace SOLRTest
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
Startup.Init<Customer>("http://service...local:8080/solr/msglog_pilot...");
}
}
}
Errors which I get is:
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0119: 'SOLR4.Models.Customer' is a 'type', which is not valid in the given context
Source Error:
Line 12: </body>
Line 13: </html>
Line 14: **<% foreach (var izpis in SOLR4.Models.Customer)**
Line 15: { %>
Line 16: <li>
How to write correct code for View in MVC4, and also is my code for simple query in Controller correct.
Please help. Thanks for ideas.
Daniel
<% foreach (var izpis in SOLRTest.Models.Customer)
{ %>
<li>
<ul>
<%= Html.SolrFieldPropName<Customer>(izpis) %>
</ul>
</li>
<% } %>
SOLRTest.Models.Customer is a type, not a variable. You cannot foreach over a Type. Change your foreach to loop over your actual model variable.
You are not returning your model from your controller either.

MVC, Views and System.Data.Entity

I have a Repository Project that is added to my MVC application.
Within my C# code, of the MVC Web App, I have had to add a reference to System.Data.Entity so that I can access the objects from my Repository.
So the following fails if I do not have the reference added;
DataRepository<Store> repo = new DataRepository<Store>();
List<Store> allSorted = repo.All(x => x.name);
Now I want to pass that list to my Partial View, which sits within a FVM and it's the FVM that I pass to the Partial View.
So the index.aspx code;
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<StoresFVM>" %>
<% Html.RenderPartial("StoreList", Model.StoreListFVM); %>
And the ASCX code;
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<StoreListFVM>" %>
<%
SelectList storeList = new SelectList(Model.Stores.Select(x => new { Value = x.number, Text = x.name }),"Value","Text");
%>
<%= Html.DropDownList("SelectedStore", storeList) %>
However, I get an error informing me that I need to include a reference to System.Data.Entity in the ascx. I don't get why for one.
I have tried adding the namespace to the web.config file and I have tried importing the namespace at the top of the ascx page.
Thoughts?
EDIT
\nasfile02\Visual Studio
2010\Projects\TOM\TOM\Views\Stores\PartialViews\StoreList.ascx(4):
error CS0012: The type 'System.Data.Objects.DataClasses.EntityObject'
is defined in an assembly that is not referenced. You must add a
reference to assembly 'System.Data.Entity, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089'.
EDIT
namespace TOM.FormViewModels
{
public class StoresFVM
{
public StoreListFVM StoreListFVM { get; set; }
}
}
namespace TOM.FormViewModels
{
public class StoreListFVM
{
public List<Store> Stores { get; set; }
}
}
You should make sure the web.config looks as following:
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
Also described at: https://stackoverflow.com/a/3611040/1737862

ViewBag RuntimeBinderException (MVC 4, ASPX)

I started up a Default MVC 4 project using the ASPX engine (not Razor), and everything works fine.
I can use
<% Model.Name %>
and
<% Model.Rating %>
for book ratings (instead of the Restaurant Review that is up on the asp.net/mvc tutorials site). However, my code errors on the
<% ViewBag.Message %>
...so for some reason, when inheriting from the "BookReviewer" Class within the BookReview model, I can view the Model information but not the Viewbag? Am I missing something? Code below.
[Controller]
HomeController.cs:
public class HomeController : Controller
{
var model = new BookReview()
{
Name = "Pro jQuery For Noobs",
Rating = 7
};
return View(model);
}
[Model]
BookReview.cs
namespace Bookreview.Models
{
public class BookReview
{
public string Name { get; set; }
public int Rating { get; set; }
}
}
[View]
Index.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<BookRevew.Models.BookReviewer>" %>
<asp:Content ID="indexFeatured" ContentPlaceHolderID="FeaturedContent" runat="server">
<h2>
<% ViewBag.Message %>
<% Model.Name %>
<% Model.Rating %>
</h2>
</asp:content>
As we can see by your comments, you are setting the ViewBag.Message in another controller. The ViewBag is only for data for the view that was set by the controller that served the view.
If you need to send it from another controller, you should use a parameter in your action method, then you can set the ViewBag.Message to the passed in parameter.

Parser Error Message: 'FCR2.abs' is not allowed here because it does not extend class 'System.Web.UI.Page'

Does anyone have any idea how to solve this problem please?
This is the Parser Error When I Run the Application:
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: 'FCR2.abs' is not allowed here because it does not extend class 'System.Web.UI.Page'.
Source Error:
Line 1: <%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="404.aspx.cs" Inherits="FCR2.abs" %>
Line 2: <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
Line 3: </asp:Content>
Source File: /404.aspx Line: 1 `enter code here`
This is my 404.aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="404.aspx.cs" Inherits="FCR2.abs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Page Not Found</h1>
<p>You have come here by mistake or the page you are trying to view is no longer availible.</p>
<p>Go back to the Home Page</p>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
This is the 404.aspx.cs code:
namespace FCR2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
This is the 404.aspx.designer.cs code:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FCR2 {
public partial class abs {
}
}
Make sure you are using the same class names for that part of your code.
If you are using abs, you need to rename this like that:
namespace FCR2
{
public partial class abs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
}
}
}
Not sure as what you are trying over here
public partial class abs {
}
This is defined as partial class and is not inhesriting for Page (as it happens for WebForm1)
and your inherits points out to Inherits="FCR2.abs" which i believe should be WebForm1 instead of abs
Try right click Convert to Web Application and that should generate the proper designer file for you

Can't find ASP.NET master page

I'm trying to get my content page to be able to access an ASP:Literal on a master page.
I have my content page as:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="viewProduct.aspx.cs" Inherits="AlphaPackSite.viewProduct" Title="Hi there!" %>
<%# MasterType TypeName="Main" %>
Then my master page called Main.master has:
<asp:Literal runat="server" ID="lblBasket" />
But from the content page when I try and do:
Master.basket.Text = "test";
I get:
Error 46 The type or namespace name
'Main' could not be found (are you
missing a using directive or an
assembly reference?)
The error is on the designer page:
public new Main Master {
get {
return ((Main)(base.Master));
}
}
My master page code behind is:
namespace AlphaPack.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
this.IsLoggedIn = Request.IsAuthenticated;
}
public bool IsLoggedIn
{
get { return this.ViewState["isLoggedIn"] as bool? ?? false; }
set { this.ViewState["isLoggedIn"] = value; }
}
}
}
Is the designer within your AlphaPack.MasterPages namespace?
The MasterType isn't fully qualified, should it be? Don't you have to provide a path as well? (Not familiar with, sorry).
How does this respond if you use a MasterPageFile reference instead of a MasterType?
<%# Page Language="C#" MasterPageFile="~MasterPages/Main.Master" AutoEventWireup="true" CodeBehind="viewProduct.aspx.cs" Inherits="AlphaPackSite.viewProduct" Title="Hi there!" %>
<%# Page MasterPageFile="~/MasterPages/Main.master" .. %>
<%# MasterType VirtualPath="~/MasterPages/Main.master" .. %>
Okey, that's how it looks in my own app:
Master page (Site.master, in the root):
<%# Master Language="C#" AutoEventWireup="True" CodeBehind="Site.master.cs" Inherits="Project.SiteMaster" %>
It's code-behind:
namespace Project
{
public partial class SiteMaster : System.Web.UI.MasterPage { }
}
Content page (Test.aspx, in the root):
<%# Page Language="C#" AutoEventWireup="True" CodeBehind="Test.aspx.cs" Inherits="Project.Test" MasterPageFile="~/Site.master" Title="Test" %>
it's code-behind:
namespace Project
{
public partial class Test : System.Web.UI.Page { }
}
That's how auto-generated code looks like:
namespace Project {
public partial class SiteMaster {
/// <summary>
/// lblBasket control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal lblBasket;
}
}
So create a property but don't share the control itself, only text:
public string BasketText
{
get { return this.lblBasket.Text; }
set { this.lblBasket.Text = value; }
}

Categories