i try to create web application with highchart and this is my tutorial http://csharptrenches.wordpress.com/2013/08/21/how-to-use-highcharts-js-with-asp-net-mvc-4/ .Code in my controller and view not have some error.but i have some problem when i'm run a browser ,it's tell me about The resource can not be found .Can you tell me why and how can i do in this case. Thank you so much.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Highcharts;
using DotNet.Highcharts.Helpers;
using DotNet.Highcharts.Options;
using DotNet.Highcharts.Enums;
namespace HighCharts.Controllers
{
public class TransactionCount
{
public string MonthName { get; set; }
public int Count { get; set; }
}
public class IndexController : Controller
{
//
// GET: /Index/
public ActionResult Index()
{
var transaction = new List<TransactionCount> {
new TransactionCount(){ MonthName="January", Count=40},
new TransactionCount(){ MonthName="February", Count=20},
new TransactionCount(){ MonthName="March", Count=35},
new TransactionCount(){ MonthName="April", Count=70}
};
//change mountName & value to array
var xDataMonths = transaction.Select(i => i.MonthName).ToArray();
var yDataValue = transaction.Select(i => new object[] {i.Count}).ToArray();
var chart = new Highcharts("chart")
//choose type of graph
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Column })
//set a title
.SetTitle(new Title { Text = "financial" })
//sub title
.SetSubtitle(new Subtitle { Text = "Accounting" })
//load value to xAxis
.SetXAxis(new XAxis { Categories = xDataMonths })
//set the y title and format text
.SetYAxis(new YAxis { Title = new YAxisTitle { Text = "Values" } })
.SetTooltip(new Tooltip
{
Enabled = true,
Formatter = #"function() { return '<b>'+ this.series.name +'</b><br />'+this.x +': '+ this.y:}"
})
.SetPlotOptions(new PlotOptions
{
Column = new PlotOptionsColumn
{
DataLabels = new PlotOptionsColumnDataLabels
{
Enabled = true
},
EnableMouseTracking = false
}
})
//load data value to yAxis
.SetSeries(new[]{
new Series {Name = "Per Month", Data = new Data(yDataValue)}
});
return View(chart);
}
}
}
and this is my View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#model DotNet.Highcharts.Highcharts
<p>My Column Chart</p>
#(Model)
And this is my route config
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace HighCharts
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "IndexController", action = "ShowChart", id = UrlParameter.Optional }
);
}
}
}
The Problem is inside route config
Change
defaults: new { controller = "IndexController", action = "ShowChart", id = UrlParameter.Optional });
To
defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional });
Your controller does not has an action named ShowChart as what you provide in your codes, and for controller parameter you only need to write the actionName.
Related
I pull the tags in the news details section. The corresponding code block is below.
NewsDetail:
foreach (var item in etiketler.Take(1))
{
<span>#item</span>
}
foreach (var item in etiketler.Skip(1))
{
<span>#item</span>
}
Controller :
public ActionResult Tag(string tag, int? pageSize)
{
string id = this.RouteData.Values["tag"].ToString();
SectionServices _sectionServices = new SectionServices();
if (!pageSize.HasValue) pageSize = 1;
ViewBag.Current = pageSize;
Models.TagModel model = new Models.TagModel();
var dat = _sectionServices.getNewsByTag((int)pageSize, tag);
ViewData["etiket"] = tag;
if (dat != null)
{
ViewBag.Tag = tag;
model.getNews = dat;
return View(model);
}
return View();
}
Route Config :
routes.MapRoute(
name: "TagPage",
url: "{tag}-haberleri/{pageSize}",
defaults: new { controller = "Page", action = "Tag", pageSize = UrlParameter.Optional }
);
I get errors like "The controller for path '/Mert Hakan_haberleri / 2' was not found or does not implement IController" in log records. what is the cause of this error, clicking on tags works correctly, but I see this error in log records.
I also had this error. When I embedded the classes into a namespace, everything started working for me.
namespace PageControllers { // added this line!
public class PageController {
public ActionResult Tag() {
//code logic
return View();
}
}
}
I am working on multi language web site. it works fine with each IP_Address, the problem is that I want to make the URL changed after it renders, in the way it shows whats the language code in the URL.
here is my route config
namespace global_vrf
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{language}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, language="" }
);
}
}
}
and this is my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using global_vrf.GeoIpService;
namespace global_vrf.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string language)
{
if (language!="")
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
else if(language=="")
{
try
{
string userIpAddress = this.Request.UserHostAddress;
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
if (country_code == "FRA")
{
language = "fr-FR";
}
//and I will check the other languages here
}
catch
{
string userIpAddress = "209.95.51.176";
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
language = "en-us";
}
}
Appreciate any help. thanks
Use attribute routing in mvc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using global_vrf.GeoIpService;
namespace global_vrf.Controllers
{
RoutePrefix("Example Name")]
public class HomeController : Controller
{
public ActionResult Index(string language)
{
if (language!="")
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
else if(language=="")
{
try
{
string userIpAddress = this.Request.UserHostAddress;
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
if (country_code == "FRA")
{
language = "fr-FR";
}
//and I will check the other languages here
}
catch
{
string userIpAddress = "209.95.51.176";
ViewBag.userIpAddress = userIpAddress;
GeoIPService service = new GeoIPService();
GeoIP output = service.GetGeoIP(userIpAddress);
ViewBag.userIpAddress = userIpAddress;
var country_name = output.CountryName;
ViewBag.cnam = country_name;
var country_code = output.CountryCode;
ViewBag.ccode = country_code;
language = "en-us";
}
}
I have a route defined as follows in MVC:
routes.MapRoute(
name: "ContentNavigation",
url: "{viewType}/{category}-{subCategory}",
defaults: new { controller = "Home", action = "GetMenuAndContent", viewType = String.Empty, category = String.Empty, subCategory = String.Empty });
If I navigate to http://example.com/something/category-and-this-is-a-subcategory
It fills the variables as:
viewType: "something"
category: "category-and-this-is-a"
subCategory: "subcategory".
What I want is for the word before the first dash to always go into category, and the remaining into subcategory. So it would produce:
viewType: "something"
category: "category"
subCategory: "and-this-is-a-subcategory"
How can I achieve this?
One possibility is to write a custom route to handle the proper parsing of the route segments:
public class MyRoute : Route
{
public MyRoute()
: base(
"{viewType}/{*catchAll}",
new RouteValueDictionary(new
{
controller = "Home",
action = "GetMenuAndContent",
}),
new MvcRouteHandler()
)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
if (rd == null)
{
return null;
}
var catchAll = rd.Values["catchAll"] as string;
if (!string.IsNullOrEmpty(catchAll))
{
var parts = catchAll.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 1)
{
rd.Values["category"] = parts[0];
rd.Values["subCategory"] = parts[1];
return rd;
}
}
return null;
}
}
that you will register like that:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("ContentNavigation", new MyRoute());
...
}
Now assuming that the client requests /something/category-and-this-is-a-subcategory, then the following controller action will be invoked:
public class HomeController : Controller
{
public ActionResult GetMenuAndContent(string viewType, string category, string subCategory)
{
// viewType = "something"
// category = "category"
// subCategory = "and-this-is-a-subcategory"
...
}
}
OK so I would love to know how to check witch routes are currently in place in my MVC app, because currently I have this setup for MVC3 app and as far as I know everything is correct, but the "Data" route still does not work:
global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using InteractiveAnalysis.Common;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Diagnostics;
using InteractiveAnalysis.App_Start;
using System.Web.Optimization;
namespace InteractiveAnalysis
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : ToolsFramework.Mvc.ToolsFrameworkHttpApplicationBase
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Excel", // Route name
"excel", // URL with parameters
new { controller = "Excel", action = "Index"} // Parameter defaults
);
routes.MapRoute(
"Data", // Route name
"data", // URL with parameters
new { controller = "Data", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Version", // Route name
"version/{action}", // URL with parameters
new { controller = "Version", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Main", // Route name
"{ver}", // URL with parameters
new { controller = "Main", action = "Index", ver = UrlParameter.Optional } // Parameter defaults
);
/*
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("cache/{action}/{id}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Main", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
*/
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
UnityObject.Register();
ToolsFramework.Cache.OutputCacheHandeler.addCacheKey(UnityObject.APPLICATION_NAME);
//OldBundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_Error(object sender, EventArgs e)
{
Response.Clear();
Exception exception = Server.GetLastError();
HttpException httpException = (exception.GetBaseException() as HttpException);
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 501: //function not implemented
Server.ClearError();
Response.Write(exception.Message);
return;
}
}
#if !DEBUG
if (Euroland.Azure.Utilities.AzureEnvironment.IsAvailable)
{
EventLog.WriteEntry(InteractiveAnalysis.Common.UnityObject.APPLICATION_NAME, "Error:\r\n\r\n" + exception.Message + "\r\n\r\nStack Trace:\r\n" + exception.StackTrace, EventLogEntryType.Error);
}
else
{
Exception exx = Server.GetLastError().GetBaseException();
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(exx, true);
string Category = "ASP.NET error";
string ASPCode = "N/A";
string ASPDescription = exx.ToString();
if (ASPDescription.Length > 500) { ASPDescription = ASPDescription.Substring(0, 500); }
string Column = trace.GetFrame(0).GetFileColumnNumber().ToString();
string Description = exx.Message.ToString();
if (Description.Length > 500) { Description = Description.Substring(0, 500); }
string File = trace.GetFrame(0).GetFileName();
string Line = trace.GetFrame(0).GetFileLineNumber().ToString();
string Number = "N/A";
string Source = trace.GetFrame(0).GetMethod().Name;
if (Source.Length > 500) { Source = Source.Substring(0, 250); }
string ServerName = HttpContext.Current.Server.MachineName; //Request.ServerVariables["SERVER_NAME"];
string ServerIP = Request.ServerVariables["LOCAL_ADDR"];
string RemoteIP = Request.ServerVariables["REMOTE_ADDR"];
string UserAgent = Request.ServerVariables["HTTP_USER_AGENT"];
string Referer = Request.ServerVariables["REFERER"];
string URL = Request.Url.ToString();
//currently it can function in the local enviroment
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocaleErrorConnectionString"].ToString());
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "spInsertServerError";
myCommand.Connection = conn;
myCommand.Parameters.AddWithValue("#Category", Category);
myCommand.Parameters.AddWithValue("#ASPCode", ASPCode);
myCommand.Parameters.AddWithValue("#ASPDescription", ASPDescription);
myCommand.Parameters.AddWithValue("#Column", Column);
myCommand.Parameters.AddWithValue("#Description", Description);
myCommand.Parameters.AddWithValue("#File", File);
myCommand.Parameters.AddWithValue("#Line", Line);
myCommand.Parameters.AddWithValue("#Number", Number);
myCommand.Parameters.AddWithValue("#Source", Source);
myCommand.Parameters.AddWithValue("#ServerName", ServerName);
myCommand.Parameters.AddWithValue("#ServerIP", ServerIP);
myCommand.Parameters.AddWithValue("#RemoteIP", RemoteIP);
myCommand.Parameters.AddWithValue("#UserAgent", UserAgent);
myCommand.Parameters.AddWithValue("#Referer", Referer);
myCommand.Parameters.AddWithValue("#URL", URL);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
}
catch { }
finally
{
if (conn.State != ConnectionState.Closed) { conn.Close(); }
//Server.ClearError();
}
}
#endif
}
}
}
DataController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Globalization;
using InteractiveAnalysis.Models;
using ToolsFramework;
namespace InteractiveAnalysis.Controllers
{
public class DataController : Controller
{
//
// GET: /Data/
public string Index()
{
return "something";
}
}
}
But every time I check "localhost:62570/data/" I get a 404 and I just do not get it. What am I missing why hasn't the "Data" route taken hold? As far as I know I have done everything correctly.
The best and easiest way to check/debug routes is using the Phil Haack's route debugger, you can install it with following nuget package
{Sorry new to JSON}
I need to build up an array of resources (Users) and pass it in to my view, might be a better way than what ive done below? (Demo)
My model is simply
public class ScheduleUsers
{
public string Resource{ get; set; }
}
On my controller
var users = new JsonArray(
new JsonObject(
new KeyValuePair<string,JsonValue>("id","1"),
new KeyValuePair<string,JsonValue>("name","User1")),
new JsonObject(
new KeyValuePair<string, JsonValue>("id", "2"),
new KeyValuePair<string, JsonValue>("name", "User2"))
);
model.Resources = users.ToString();
Why don't you just return a list of entities as a JSON result, like:
public class CarsController : Controller
{
public JsonResult GetCars()
{
List<Car> cars = new List<Car>();
// add cars to the cars collection
return this.Json(cars, JsonRequestBehavior.AllowGet);
}
}
It will be converted to JSON automatically.
I did this and this works
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
//Serialize
js.Serialize(GetResources(), sb);
public List<ScheduledResource> GetResources()
{
var res = new List<ScheduledResource>()
{
new ScheduledResource()
{
id = "1",
color = "blue",
name = "User 1"
},
new ScheduledResource()
{
id = "2",
color = "black",
name = "User 2"
},
};
return res;
}