I am working in mvc5. I made a simple action link in a view using this syntax
#Html.ActionLink("Manage List", "Index", new { #class = "ManageLink" });
But css was not working untill i added controller name like this:
#Html.ActionLink("Manage List", "Index",new { controller = "ControllerName" }, new { #class = "ManageLink" });
I want to know why we need to define controller name here while it is quite obvious that every view is related to some action method of a controller ? I am very new to mvc so need to know these kind of things.
Thanks for the help.
You could also have fixed this by simply specifying the name of the optional parameter you wanted to set:
#Html.ActionLink("Manage List", "Index", htmlAttributes: new { #class = "ManageLink" });
Otherwise, the Razor engine has to try to figure out which overload of the ActionLink method you're trying to call; sounds like in your case it thought the third argument was for the routeValues parameter.
This would also work:
#Html.ActionLink("Manage List", "Index", "ControllerNameHere", new { #class = "ManageLink" });
Related
Is there an equivalent to Response.Redirect("~/Controller/") in Asp.Net Core 2 ?
I don't want to use ViewComponent. Instead of, I want call a Controller and an action method from a view.
#using Jahan.Blog.Web.Mvc.Models
#{
ViewBag.Title = "Home Page";
}
<header>
<h1> Blog </h1>
</header>
<div class="blog-description">
<p>...</p>
</div>
#{ Response.Redirect("~/Article/");}
Try this if within the controller method:
RedirectToAction("yourActionName", "YourControllerName");
or:
Url.Action("YourActionName", "YourControllerName");
This can also be used with parameters as defined in your AppStart -> RouteConfig.cs file
i.e
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "YourControllerName", action = "YourActionName", id =
UrlParameter.Optional }
);
to pass parameters simply add new keyword for get method
Url.Action("YourActionName", "YourControllerName", new { id = id });
for Post Method use
Url.Action("YourActionName", "YourControllerName", new { "your variable" = id });
You should return a result from your action.
Views should not contain logic like that; you should move all such logic to an action or filter.
You are redirecting from the view... a view in ASP MVC Core 2 or Razor Pages do not have access to the context of the request, so they cant redirect...
I have a role based #html.ActionLink() .Which show or hide link based on user permission.ASP.NET MVC5 Default #html.ActionLink() works fine.
But i want to pass angularjs value as a route value.
#Html.ActionLink("Edit", "Edit", "Branches", new { id = "{{branch.BranchId}}" })
but this code render following code
Edit
i found this link but can't find a solution.
#Html.ActionLink and Angularjs value?
I want to pass angularjs value using actionLink() not Url.Action()
Thanks
This could work for you. Just remove the controller name from the parameters.
#Html.ActionLink("Edit", "Edit", new { id = "{{branch.BranchId}}" })
Or like this with controller name
#Html.ActionLink("Edit", "Edit", "Branches", new { id = "{{branch.BranchId}}" }, null)
Or you can try this
#{
var link = Url.Action("Edit", "Branches", new { id = "{{branch.BranchId}}" });
link = HttpUtility.UrlDecode(link);
}
Edit
How do you make a Razors helper "Dropdownlist" or what arguments would have to pass to make it editable. For example if I want to scroll down it should let me or if I want type Instead it should let aswell.
#Html.DropDownList("CustomerId", null, htmlAttributes: new { #class = "form-control" } )
Also, if you I choose to use twitter-typeahead with EF razors how do use the "Editfor" so that once the user click on the right item, it sends the ID of that item to the database. In-other words, how do use a navigation property with razors "Editfor" helper.
#Html.EditorFor(model => model.CustomerId, null, "customer",new {htmlAttributes = new { #class = "form-control" } })
I will try to help you convert the basic example of the following page to a razor page equivalent.
http://twitter.github.io/typeahead.js/examples/
You must know that this jquery plugin displays just a list of strings and the user will select one of the values and then you will have to find the id using C# code. I will just show you how to implement the twitter typehead using razor pages but you will have to make some extra work in order to get the id.
First of all you will need the html part
<div id="the-basics">
<input class="typeahead" type="text" placeholder="States of USA">
</div>
Next you need to declare your list using C#.
List<string> Values = new List<string> { "Value 1", "Value 2", "Value 3" };
Now you will have the following HTML.
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var states = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Values));
$('#the-basics .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(states)
});
I hope it helps.
Is it possible to assign my own class to the HTML.DropDownListFor() helper?
One of the overloaded method has an object htmlAttributes as last parameter in which you can specify extra attributes to be added to the generated html:
Html.DropDownListFor(..., new { "class" = "myclassname" };
http://msdn.microsoft.com/library/ee703670.aspx
Didier's answer is mostly correct, but to define a class value in htmlAttributes object, you need to use this syntax:
Html.DropDownListFor(..., new { #class = "myclassname" } );
The "#" is to let the compiler know that this is not the keyword "class". Using "class" will result in a compilation error.
You can use any of the below logic.
#Html.DropDownList("CourseId", new List<SelectListItem>(), new {#class="myclassname"} )
OR
#Html.DropDownList("CourseId", (IEnumerable<SelectListItem>)ViewBag.CourseId, new { #class="myclassname" })
OR
#Html.DropDownListFor(x => x.CourseId, (IEnumerable<SelectListItem>)ViewBag.CourseId, new { #class = "myclassname" })
In my layout page, the links to the main sections that make up my site are rendered with a call like this:
#SiteSectionLink("index", "blog", "blog")
Where SiteSectionLink is a helper that looks like this:
#helper SiteSectionLink(string action, string controller, string display)
{
<li>
<h1>
<a class="site-section" href="#Url.Action(action, controller)">#display</a></h1>
</li>
}
On the actual blog page, all links also refer to the "Index" action but also specify either a date parameter (such as "blog/4-2011" or "blog/2010") that is used to filter the posts by a date period. In addition to that, there's also an optional postID parameter that is used to refer to a specific post.
To accomplish that, I have the following routes:
routes.MapRoute(
"Blog",
"blog/{date}/{postID}",
new
{
controller = "blog",
action = "index",
date = UrlParameter.Optional,
postID = UrlParameter.Optional
}
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Now, the problem is that when I have clicked a link that is something like "blog/11-2010" or "blog/11-2010/253" then the link in my layout page that refers to my blog in general now also refers to that same URL when I want it to just link to "blog/", not "blog/11-2010".
If I change the SiteSectionLink helper to explicitly pass in null for date and postID like this:
<a class="site-section" href="#Url.Action(action, controller,
new { date = (string)null, postID = (int?)null})">#display</a></h1>
The current route values are still used but now it looks like "blog?date=11-2010".
I saw this similar question but the accepted answer doesn't work for me, and I don't use ActionLink in the first place and I suspect that ActionLink would use Url.Action under the hood.
While the issue you are experiencing is not quite the behavior detailed by Phil Haack in this blog post regarding a bug with MVC3 routing and a route with two optional parameters, I would suggest applying the fix described in Phil's post.
I also would suggest never creating a route with two optional parameters, and instead follow the pattern of breaking the desired routing into two separate routes.
Yes Url.Action method puts the parameters in the querystring.
You can change your helper like this:
#helper SiteSectionLink(string action, string controller, string display, string date = null, string id=null)
{
<li>
#if (date == null)
{
<h1><a class="site-section" href="~/blog/#controller/#action">#display</a></h1> // simple workaround or better use P. Haack workaround
}
else
{
<h1><a class="site-section" href="#Url.RouteUrl("blog", new { action = #action, controller = #controller, date = #date, id = #id })">#display</a></h1>
}
</li>
}
So you can use SiteSelectionLink like these:
#SiteSectionLink("Index", "Blog", "test", "2011", "4")
#SiteSectionLink("Index", "Blog", "test2", "2011")
#SiteSectionLink("Index", "Blog", "test3")