Silverlight - Routing question - asp.net-mvc

I have the following route in global.asax:
routes.MapRoute(
"IdeaShort",
"Idea/{id}",
new { PortalID = NEOGOV_Ideas.Models.Util.DefaultPortal().PortalID, IdeaType = "All", controller = "Home", action = "Idea", id = "" });
one problem - PortalID and IdeaType is linked with Idea, so I should get Idea from id before set PortalID and IdeaType. How to do it? Thanks

Just don't make PortalID and IdeaType incoming parameters of your action, but rather determine them inside the action method:
public ActionResult Idea(int id)
{
var PortalID = GetPortalID(id); //get PortalID here
var IdeaType = GetIdeaType(id); //get IdeaType here
//go on with the whole set of parameters you need
}

Related

How to utilize a user-defined url action in asp,net mvc?

My hope is to provide a method to end users that will let them enter a value 'SmallBuildingCompany', and then use this value to make a custom url that will redirect to an informational view. so for example, www.app.com/SmallBuildingCompany. Can anyone point me to some information to help on this?
edited 161024
My attempt so far:
I added this within RouteConfig.
RouteTable.Routes.MapRoute(
"Organization",
"O/{uniqueCompanyName}",
new { controller = "Organization", action = "Info" }
and added a new controller method and view under the organization controller.
public async Task<ActionResult> Info(string uniqueCompanyName)
{
var Org = db.Organizations.Where(u => u.uniqueCompanyName == uniqueCompanyName).FirstOrDefault();
Organization organization = await db.Organizations.FindAsync(Org.OrgId);
return View("Info");
}
You can achieve this by using the SmallBuildingCompany part of the URL as a parameter for an action that is used to display every informational view.
Set up the Route in Global.asax.cs to extract the company name as parameter and pass it to the Index action of CompanyInfoController:
protected void Application_Start() {
// Sample URL: /SmallBuildingCompany
RouteTable.Routes.MapRoute(
"CompanyInfo",
"{uniqueCompanyName}",
new { controller = "CompanyInfo", action = "Index" }
);
}
Note that this Route will probably break the default route ({controller}/{action}/{id}), so maybe you want to prefix your "Info" route:
protected void Application_Start() {
// Sample URL: Info/SmallBuildingCompany
RouteTable.Routes.MapRoute(
"CompanyInfo",
"Info/{uniqueCompanyName}",
new { controller = "CompanyInfo", action = "Index" }
);
}
Then the CompanyInfoController Index action can use the uniqueCompanyName parameter to retrieve the infos from the database.
public ActionResult Index(string uniqueCompanyName) {
var company = dbContext.Companies.Single(c => c.UniqueName == uniqueCompanyName);
var infoViewModel = new CompanyInfoViewModel {
UniqueName = company.UniqueName
}
return View("Index", infoViewModel);
}
ASP.NET Routing

asp .net mvc routing url with custom literal

Is it possible to make url with custom literal separator that can have default parameters ?
context.MapRoute(
"Forums_links",
"Forum/{forumId}-{name}",
new { area = "Forums", action = "Index", controller = "Forum" },
new[] { "Jami.Web.Areas.Forums.Controllers" }
);
I have this as you see im using to dash to separate id from name so I can have url like:
/Forum/1-forum-name
Instead of:
/Forum/1/forum-name
I see the problem is I'm using multiple dashes. And routing engine don't know which one to separate. But overalll it doesn't change my question because I want to use multiple dashes anyway.
Very interesting question.
The only way I could come up with is much like Daniel's, with one extra feature.
context.MapRoute(
"Forums_links",
"Forum/{forumIdAndName}",
new { area = "Forums", action = "Index", controller = "Forum" },
new { item = #"^\d+-(([a-zA-Z0-9]+)-)*([a-zA-Z0-9]+)$" } //constraint
new[] { "Jami.Web.Areas.Forums.Controllers" }
);
That way, the only items that will get matched to this route are ones formatted in the pattern of:
[one or more digit]-[zero or more repeating groups of string separated by dashes]-[final string]
From here you would use the method Daniel posted to parse the data you need from the forumIdAndName parameter.
One way to achieve this could be by combining id and name into the same route value:
context.MapRoute(
"Forums_links",
"Forum/{forumIdAndName}",
new { area = "Forums", action = "Index", controller = "Forum" },
new[] { "Jami.Web.Areas.Forums.Controllers" }
);
And then extract the Id from it:
private static int? GetForumId(string forumIdAndName)
{
int i = forumIdAndName.IndexOf("-");
if (i < 1) return null;
string s = forumIdAndName.Substring(0, i);
int id;
if (!int.TryParse(s, out id)) return null;
return id;
}

ASPMvc Routing Issues with legacy url

I have got a legacy url that I cannot change, which is output on a page which needs to now post to a new MVC version of the page:
http://somesite.com/somepage?some-guid=xxxx-xxxx
Now I am trying to map this to a new controller but I need to get the some-guid into my controller:
public class MyController : Controller
{
[HttpGet]
public ActionResult DisplaySomething(Guid myGuid)
{
var someResult = DoSomethingWithAGuid(myGuid);
...
}
}
I can change the controller and routes as much as I like, however the legacy url cannot change. So I am a bit stumped as to how I can get access to the some-guid.
I have tried routing with the ?some-guid={myGuid} but the routing doesn't like the ?, so then I tried to let it autobind, but as it contains hyphens it doesn't seem to bind. I was wondering if there was any type of attribute I could use to hint that it should bind from a part of the querystring...
Any help would be great...
I would have thought you would have done a route a bit like this..
routes.MapRoute(
"RouteName", // Name the route
"somepage/{some-guid}", // the Url
new { controller = "MyController", action = "DisplaySomething", some-guid = UrlParameter.Optional }
);
The {some-guid} part of URL matches your url parmater and passes it to the controller.
So if you have your action like so :
public ActionResult DisplaySomething(Guid some-guid)
{
var someResult = DoSomethingWithAGuid(some-guid);
...
}
Give that a go and see how you get on..
routes.MapRoute(
"Somepage", // Route name
"simepage", // URL with parameters
new { controller = "MyController", action = "DisplaySomething"
);
And then in your controller:
public class MyController : Controller {
public ActionResult DisplaySomething(Guid myGuid)
{
var someResult = DoSomethingWithAGuid(myGuid);
...
}
}
Try this:
routes.MapRoute("SomePageRoute","Somepage",
new { controller = "MyController", action = "DisplaySomething" });
And then in your controller:
public ActionResult DisplaySomething() {
Guid sGuid = new Guid(Request.QueryString["some-guid"].ToString());
}

ASP.NET MVC: Route to URL

What's the easiest way to get the URL (relative or absolute) to a Route in MVC? I saw this code here on SO but it seems a little verbose and doesn't enumerate the RouteTable.
Example:
List<string> urlList = new List<string>();
urlList.Add(GetUrl(new { controller = "Help", action = "Edit" }));
urlList.Add(GetUrl(new { controller = "Help", action = "Create" }));
urlList.Add(GetUrl(new { controller = "About", action = "Company" }));
urlList.Add(GetUrl(new { controller = "About", action = "Management" }));
With:
protected string GetUrl(object routeValues)
{
RouteValueDictionary values = new RouteValueDictionary(routeValues);
RequestContext context = new RequestContext(HttpContext, RouteData);
string url = RouteTable.Routes.GetVirtualPath(context, values).VirtualPath;
return new Uri(Request.Url, url).AbsoluteUri;
}
What's a better way to examine the RouteTable and get a URL for a given controller and action?
Use the UrlHelper class: http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.aspx
You should be able to use it via the Url object in your controller. To map to an action, use the Action method: Url.Action("actionName","controllerName");.
A full list of overloads for the Action method is here: http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action.aspx
so your code would look like this:
List<string> urlList = new List<string>();
urlList.Add(Url.Action("Edit", "Help"));
urlList.Add(Url.Action("Create", "Help"));
urlList.Add(Url.Action("Company", "About"));
urlList.Add(Url.Action("Management", "About"));
EDIT: It seems, from your new answer, that your trying to build a sitemap.
Have a look at this Codeplex project: http://mvcsitemap.codeplex.com/. I haven't used it myself, but it looks pretty solid.
How about this (in the controller):
public IEnumerable<SiteMapEntry> SiteMapEntries
{
get
{
var entries = new List<SiteMapEntry>();
foreach (var route in this.Routes)
{
entries.Add(new SiteMapEntry
(
this.Url.RouteUrl(route.Defaults),
SiteMapEntry.ChangeFrequency.Weekly,
DateTime.Now,
1F));
}
return entries;
}
}
Where the controller has member:
public IEnumerable<Route> Routes
Take note of:
this.Url.RouteUrl(route.Defaults)

Passing multiple parameters to a controller?

ok. simple one that is wrapping my brain
I have a method that I have in the controller
public ActionResult Details(string strFirstName, string strLastName)
{
return View(repository.getListByFirstNameSurname(strFirstName, strLastName)
}
How do i get multiple parameters from the URL to the controller?
I dont want to use the QueryString as it seems to be non-mvc mind set.
Is there a Route? Or Other mechanism to make this work? Or am I missing something altogehter here with MVC
EDIT
the url that I am trying for is
http://site.com/search/details/FirstName and Surname
so if this was classic asp
http://site.com/search/details?FirstName+Surname
But i feel that i have missed understood something which in my haste to get to working code, I have missed the point that there really should be in a put request - and I should collect this from the formcollection.
Though might be worth while seeing if this can be done - for future reference =>
For example, suppose that you have an action method that calculates the distance between two points:
public void Distance(int x1, int y1, int x2, int y2)
{
double xSquared = Math.Pow(x2 - x1, 2);
double ySquared = Math.Pow(y2 - y1, 2);
Response.Write(Math.Sqrt(xSquared + ySquared));
}
Using only the default route, the request would need to look like this:
/simple/distance?x2=1&y2=2&x1=0&y1=0
We can improve on this by defining a route that allows you to specify the parameters in a cleaner format.
Add this code inside the RegisterRoutes methods within the Global.asax.cs.
routes.MapRoute("distance",
"simple/distance/{x1},{y1}/{x2},{y2}",
new { Controller = "Simple", action = "Distance" }
);
We can now call it using /simple/distance/0,0/1,2
Something like this?:
routes.MapRoute("TheRoute",
"{controller}/{action}/{strFirstName}/{strLastName}",
new { controller = "Home", action = "Index", strFirstName = "", strLastName = "" }
);
or:
routes.MapRoute("TheRoute2",
"people/details/{strFirstName}/{strLastName}",
new { controller = "people", action = "details", strFirstName = "", strLastName = "" }
);
UPDATED:
This route should be placed before "Default" route:
// for urls like http://site.com/search/details/FirstName/Surname
routes.MapRoute("TheRoute",
"search/details/{strFirstName}/{strLastName}",
new { controller = "search", action = "details", strFirstName = "", strLastName = "" }
);
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
Use hidden values in your form
<%= Html.Hidden("strFirstName", Model.FirstName)%>
<%= Html.Hidden("strLastName", Model.LastName)%>
and the model binder will do the binding
public ActionResult Details(string strFirstName, string strLastName)
{
return View(repository.getListByFirstNameSurname(strFirstName, strLastName)
}
It is also possible to use FormCollection:
public ActionResult Details(int listId, FormCollection form)
{
return View(rep.getList(form["firstName"], form["lastName"])
}
Likewise, if the HTTP request contains a form value with the exact same name (case sensitive), it will automatically be passed into the ActionResult method.
Also, just to be clear, there is nothing un-MVC about querystring parameters.
I also had the same problem once and what I did was use the Ajax call inside the jQuery function. First I selected all parameter values using jQuery selectors. Below is my jQuery function.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#btnSendNow').click(function () {
var grid = $('#Patient-kendo-Grid').data('kendoGrid');
var location = $('#EmailTempalteLocation option:selected').text();
var appoinmentType = $('#EmailTemplateAppoinmentType option:selected').text();
var emailTemplateId = $('#EmailTemplateDropdown').val();
var single = $('input:radio[name=rdbSingle]:checked').val();
var data = grid.dataSource.view();
var dataToSend = {
patients: data,
place: location,
appoinment: appoinmentType,
rdbsingle: single,
templateId: emailTemplateId
};
debugger;
$.ajax({
url: 'Controller/Action',
type: 'post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataToSend)
});
});
});
</script>
My controller method has five parameters and it is as below.
[HttpPost]
public ActionResult SendEmailToMany(List<PatientModel> patients, string place, string appoinment, string rdbsingle, string templateId)
{
emailScheduleModel = new EmailScheduleModel();
AmazonSentEmailResultModel result;
List<string> _toEmailAddressList = new List<string>();
List<string> _ccEmailAddressList = new List<string>();
List<string> _bccEmailAddressList = new List<string>();
IEmailTemplateService emailTemplateService = new EmailTemplateService();
EmailTemplateContract template = emailTemplateService.GetEmailTemplateById(new Guid(templateId));
emailScheduleModel.EmailTemplateContract = new EmailTemplateContract();
emailScheduleModel.EmailTemplateContract = template;
}
It is working fine in my developments.
For further details please follow the below url.
http://dushanthamaduranga.blogspot.com/

Resources