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";
}
}
Related
Hello All I added a Controller in my project like this:-
using Aero.Api.Models.ViewModels;
using Aero.Common.Interface;
using Aero.Data.Interface;
using Microsoft.Web.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Aero.Api.Controllers
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/province")]
public class ProvinceController : BaseApiController
{
private IUserService _userService { get; set; }
// GET: States
public ProvinceController(IUserService userService, IMappingHelper mapper) :
base(mapper)
{
_userService = userService;
}
public List<StateProvinceModel> Get()
{
List<StateProvinceModel> states = new List<StateProvinceModel>();
StateProvinceModel stateProvince = new StateProvinceModel()
{
Id = "BC",
Value = "BC - British Columbia",
Name = "British Columbia",
Country = "Canada"
};
StateProvinceModel stateProvince1 = new StateProvinceModel()
{
Id = "QB",
Value = "QB- Quebec",
Name = "Quebec",
Country = "Canada"
};
StateProvinceModel stateProvince2 = new StateProvinceModel()
{
Id = "ON",
Value = "ON- Ontario",
Name = "Ontario",
Country = "Canada"
};
states.Add(stateProvince);
states.Add(stateProvince1);
states.Add(stateProvince2);
StateProvinceModel stateProvince3 = new StateProvinceModel()
{
Id = "IL",
Value = "IL - Illinois",
Name = "Illinois",
Country = "United States"
};
StateProvinceModel stateProvince4 = new StateProvinceModel()
{
Id = "GA",
Value = "GA-Georgia",
Name = "Georgia",
Country = "United States"
};
StateProvinceModel stateProvince5 = new StateProvinceModel()
{
Id = "NY",
Value = "NY- New York",
Name = "New York",
Country = "United States"
};
states.Add(stateProvince3);
states.Add(stateProvince4);
states.Add(stateProvince5);
return states;
}
}
}
when I try to call the Get method from browser like this:- http://localhost:44300/api/v1/province I get an error that the resource was not found. Other Urls on existing controllers work. For example a Url like this:- http://localhost:44300/api/v1/properties works perfectly fine.
Can anyone tell me what is going on ?
You should inherit your contoller class to ApiController instead of BaseApiContoller.
Ex: public class GoaAPIController : ApiController
Sir, You can Try changing The Method Name .
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.
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
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"];
}
I am trying to create view page at run time means, when the user type some text in textbox at run time then the view page with that name should get created.
May be my code can help you with this
Controller and descendant of ViewPage:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using Site.Models;
using System.Text.RegularExpressions;
using System.Web.Mvc.Html;
namespace Site.Controllers
{
public class MPSViewPage : ViewPage
{
// Here master page is being seted
protected override void OnPreInit(EventArgs e)
{
Random rnd = new Random();
int i = rnd.Next(0, 20);
string masterPageName = (i % 2) == 0 ? "Admin.Master" : "Main.Master";
string pathMasterPageFile = "~/Views/Shared/" + masterPageName;
MasterPageFile = pathMasterPageFile;
base.OnPreInit(e);
}
protected override void OnInitComplete(EventArgs e)
{
//List of ContentPlaceHolder's id is being got. See later
MasterPageAnalizer analizer = new MasterPageAnalizer();
IList<string> contentHolders = analizer.GetBodyPlaceholders(Regex.Match(MasterPageFile, "[^/]*$").ToString());
//Add content to ContentPlaceHolder
foreach (string holder in contentHolders)
{
ContentPlaceHolder placeHolder = (ContentPlaceHolder)Master.FindControl(holder);
if (placeHolder != null)
{
Content content = new Content();
placeHolder.Controls.Add(content);
//Set function for render each content
content.SetRenderMethodDelegate(RenderIndexDeletegate);
}
}
base.OnInitComplete(e);
}
protected void RenderIndexDeletegate(HtmlTextWriter w, Control c)
{
//You can use any html helpers for rendering content
w.Write("Render to <b>" + ((Content)c).Parent.ID +
"</b> url: " + Request.Params["URL"] +
" with query parameter " + ViewData["parameters"] + " <br />" +
Html.Action("GetHtmlStatic", "HtmlStatic", new{area = "HtmlStatic"}));
}
}
public class IndexController : Controller
{
public ActionResult Index(string parameters)
{
ViewData["parameters"] = parameters;
return View();
}
}
}
Master page analizer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
namespace Site.Models
{
public class MasterPageAnalizer
{
private DirectoryInfo dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "Views\\Shared\\");
public IList<string> MasterPages{
get
{
IList<String> masterPageNames = new List<string>();
FileInfo[] files = dirInfo.GetFiles("*.Master");
foreach (FileInfo file in files)
{
masterPageNames.Add(file.Name);
}
return masterPageNames;
}
}
public IList<string> GetBodyPlaceholders(string masterPageName)
{
IList<string> placeholders = new List<string>();
string masterPagePath = dirInfo + masterPageName;
if (File.Exists(masterPagePath))
{
string masterPageContent = File.ReadAllText(masterPagePath);
Regex expression = new Regex(#"<asp:ContentPlaceHolder.*?ID=""(?<placeHolderId>\w+)"".*?>");
masterPageContent = Regex.Match(masterPageContent, "<body>(.|\n)*</body>",RegexOptions.Multiline).ToString();
MatchCollection matches = expression.Matches(masterPageContent);
foreach (Match match in matches)
{
placeholders.Add(match.Groups["placeHolderId"].Value);
}
}
return placeholders;
}
}
}
Simple view:
<%# Page Title="" Language="C#" Inherits="Site.Controllers.MPSViewPage" %>
Good Luck.
Everything is possible. But if you are after to create a project like CMS, it's not right approach. You have to store the pages' information (such as title, description and etc.) in a data store. Thus, you have merely a single page.