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.
Related
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) %>" >
I'm trying something new (to me) in using an abstract base class for my layout viewmodel.
The problem is that when I run the site as is, it throws a very cryptic (to me) exception. What does this exception mean, and what might I do to resolve it?
Layout
#model MyApp.Core.ViewModels.LayoutViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>#Model.Title</title>
</head>
<body>
<div>
#RenderBody()
</div>
</body>
</html>
Index
#model MyApp.Core.ViewModels.Home.IndexViewModel;
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>#Model.Body</h1>
LayoutViewModel
namespace MyApp.Core.ViewModels
{
public abstract class LayoutViewModel
{
public string Title { get; set; }
}
}
IndexViewModel
namespace MyApp.Core.ViewModels.Home
{
public class IndexViewModel : LayoutViewModel
{
public string Body { get; set; }
}
}
Controller
[HttpGet]
public ActionResult Index()
{
var model = new IndexViewModel
{
Title = "Hello World",
Body = "Hello World"
};
return View(model);
}
And the Exception
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: CS1003: Syntax error, '>' expected
Source Error:
Line 27:
Line 28:
Line 29: public class _Page_Views_Home_Index_cshtml :
System.Web.Mvc.WebViewPage<FutureStateMobile.Core.ViewModels.Home.IndexViewModel;>
{
Line 30:
Line 31: #line hidden
Source File: c:\Users\Chase\AppData\Local\Temp\Temporary ASP.NET
Files\root\b314e0d7\36f522db\App_Web_index.cshtml.a8d08dba.yr7oemfz.0.cs
Line: 29
Compare and contrast:
Layout
#model MyApp.Core.ViewModels.LayoutViewModel
Index
#model MyApp.Core.ViewModels.Home.IndexViewModel;
Got it yet? Here's the answer:
one of them has a ; which shouldn't be there
I just add the line twice, and deleted... problem solved!
#model MyApp.Core.ViewModels.LayoutViewModel
#model MyApp.Core.ViewModels.Layout_OrOther_Model
Try to compile, you get an error (only one model blah, blah..)
Delete one of them.
#model MyApp.Core.ViewModels.LayoutViewModel
Compile.
That works for me!
bad:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<DSNY.Core.Interfaces.IUser>" %>
versus
good:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<DSNY.Core.Interfaces.IUser>>" %>
Compiler kept telling me it was expecting an extra >.
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.
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
Maybe this question is quite simple because I'm new to MVC2. I have a simple demo MVC project.
(1) A weak-typed view: Index.aspx
<% Html.RenderPartial("ArticalList", ViewData["AllArticals"] as List<Artical>); %>
(2) A strong-typed partial view: ArticalList.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<Artical>>" %>
<% foreach (Artical a in Model) { %>
<%= Html.ActionLink(a.Title, "About", new { id = a.ID })%><br />
<%} %>
(3) Here is the HomeController.cs
public ActionResult Index()
{
ViewData["AllArticals"] = Artical.GetArticals();
return View();
}
public ActionResult ArticalList()
{
return PartialView(Artical.GetArticals());
}
Sorry I'm using a Web-Form "angle", because if I'm using a Web-Form, when I visit Index.aspx, rendering ArticalList.ascx will call public ActionResult ArticalList(). But here I need to write Artical.GetArticals() twice in two actions. How can I put them in one?
From what I understand, as a recent newbie in MVC too, is that the partial view does not use a action method in a controller. The "ArticalList" is a reference to the partial view file only and does not make another request for an action method. The partial view gets all of it's data from the view it is called from.
Html.RenderAction might be the behavior you're getting confused with.