Use MVC helpers inside jquery.tmpl templates - asp.net-mvc

I have a simple foreach template and inside every element I want an ActionLink but that ActionLink needs to send an Id to edit the element.
The item to be templated:
<div data-bind="template: {
name: 'postsTemplate',
foreach: posts
}">
</div>
The template:
<script id="postsTemplate" type="text/html">
<h2 data-bind="text: Title"></h2>
<p class="post-info">
<p class="post-info" data-bind="text UserName"></p>
<span data-bind="Body"></span>
<p class="post-footer">
#Html.ActionLink("Comments", "IndividualPost", "Post", null, null, "comments", new {id = })
</p>
</p>
</script>
How can I send the actual post Id through the ActionLink? I mean, How I can access to the post's id without using data-bind? (Because it's a helper).

If you would implement your own ActionLink extension along the line of:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText,
string actionName, string controllerName,
object routeValues, bool noEncode)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action(actionName, controllerName, routeValues);
if (noEncode) url = Uri.UnescapeDataString(url);
var tagBuilder = new TagBuilder("a");
tagBuilder.MergeAttribute("href", url);
tagBuilder.InnerHtml = linkText;
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
Then you could make your template like:
<p class="post-info">
<p class="post-info" data-bind="text UserName"></p>
<span data-bind="Body"></span>
<p class="post-footer">
#Html.ActionLink("Comments (${CommentCount})", "IndividualPost", "Post",
new {id = "${id}"}, true)
</p>
</p>
the serverside html generated would then look like:
<p class="post-info">
<p class="post-info" data-bind="text UserName"></p>
<span data-bind="Body"></span>
<p class="post-footer">
Comments (${CommentCount})
</p>
</p>
which in turn is a perfect template in my opinion.
The reason for an ActionLink extension is the fact that the normal Html.ActionLink encodes your url to /Post/IndividualPost/%24%7Bid%7D which doesn't work for the template

option 1:
- your posts viewmodel is probably coming from the server, it could contain the link.
{
title:'post title',
commentsUrl:'/Indivdualpost/comments/123'
}
on the server
return new post { comment='post title', commentsUrl=Url.Action('Comments','Individualposts', new {id=1234}); }
and then render the comments url in the template:
<a data-bind="attr: {href:commentsUrl}">comments</a>
option 2:
script using a form
<form id="frm" action="#Url.Action("Comments","IndividualPost")>
<input type="hidden" name="id" id="postid"/>
<!-- template stuff -->
</form>
and in the template
<p class="post-footer">
<a data-bind="click:function(){ $('#postid').val(${$id}); $('#frm').submit(); }">comments</a>
</p>
(the click attribute is quite ugly, should be improved using a binding handler or a viewmodel function ( http://www.knockmeout.net/2011/08/simplifying-and-cleaning-up-views-in.html ))

Related

MVC Layout Navbar Active Hide/Show DIV

So i am going off of this example:
better way to get active pages
What I'm trying to accomplish in my _Layout.cshtml is this:
<div id="navbar">
<div><img src="~/Images/home_on.png" /></div>
<div><img src="~/Images/home_off.png" /></div>
<div><img src="~/Images/contact_on.png" /></div>
<div><img src="~/Images/contact_off.png" /></div>
</div>
The navbar div changes depending on the active page. If its home, then show "home_on.png" div. If its not display "home_off.png" and so forth.
I've used this in the past.
Declare at the top of the layout:
#{
var currentController = ViewContext.RouteData.Values["controller"] as string ?? string.Empty;
var currentAction = ViewContext.RouteData.Values["action"] as string ?? string.Empty;
string getImageSource(string basePath, string controller, string action)
{
var onOrOff = currentController.Equals(controller, StringComparison.OrdinalIgnoreCase) && currentAction.Equals(action, StringComparison.OrdinalIgnoreCase) ? "on.png" : "off.png";
return string.Format("{0}_{1}", basePath, onOrOff);
}
}
Then you can render the appropriate image based off the expected controller and action:
<div id="navbar">
<div><img src="#(getImageSource("~/Images/home", "Home", "Index"))" /></div>
<div><img src="#(getImageSource("~/Images/contact", "Home", "Contact"))" /></div>
</div>
I assume that the base ~/Home URL is going to the Index action on the HomeController, and that ~/Home/Contact is going to the Contact action on the HomeController.

How to get result of generated htmlstring from htmlhelper in controller action?

I have a custom html helper in my App_code folder.
I want to call it from my action and get generated html string.
What should I do?
My MailTemplate.cshtml contents:
#{
Layout = null;
}
#helper ContactUs(string body,string name,string email)
{
<div style="direction:rtl;font-family:Tahoma;color:#3b7a09;">
<span>از طرف:</span><span>#name</span>
<br />
<span>ایمیل:</span><span>#email</span>
<br />
<div style="background-color:#f5dfb2;font-size:13px;">
#body
</div>
</div>
}
Check below code, it has example of html helper method and that helper method use in view.
HTML helper method in App_Code(App_Code\HelperMethods.cshtml)
#helper renderheader(WebViewPage page, string displayText, string ActionName)
{
<div class="row">
<div class="span4">
#page.Html.ActionLink(displayText, ActionName, new { id = 0 }, new { #class = "btn btn-small
btn-primary" })
</div>
<div class="span4">
#page.ViewBag.ErrMsg
</div>
</div>
}
Helper Method Call in View
#HelperMethods.renderheader(this, "AddGroup" , "Create")

Form action not hitting MVC controller method

I want to do a simple file upload using Html forms. I have the following in my view:
<form action='#Url.Action("Save", "Order")' method="post" enctype="multipart/form-data" id="attachmentForm">
<div >
<label style="text-align: left;">Delivery note:</label>
</div>
<div style="float:left; ">
<input type="file" name="DeliveryNoteFile" id="DeliveryNote" style="width: 400px;" />
</div>
<div style="float:right; margin-top:10px; margin-left:5px; margin-bottom:0px;">
#(Html.Kendo().Button()
.Name("btnAddAttachment")
.HtmlAttributes( new {type = "submit"} )
.Content("Submit"))
</div>
</form>
Now here is my controller method. Controller name: Order , Method name: Save.
Why is it not hitting my controller method?
[HttpPost]
public ActionResult Save(HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var physicalPath = Path.Combine(Server.MapPath("C:\\Attachments"), fileName);
file.SaveAs(physicalPath);
}
return Content("");
}
Note that this is only a first draft. Any suggestions to improve this are also welcome.
I think in your case your button is not of type submit that is why it is not hitting controller action just try making submit button this way:
#(Html.Kendo().Button()
.Name("btnAddAttachment")
.HtmlAttributes( new {type = "submit"} )
.Content("Submit"))
as # AbbasGaliyakot comment worked for the user in comment section so i m also including it here.
Change controller action parameter name from file to DeliveryNoteFile.
Please try this out. This would help.
#using (Html.BeginForm("Save", "Order", FormMethod.Post, new { enctype = "multipart/form-data", id = "attachmentForm" }))
{
<div >
<label style="text-align: left;">Delivery note:</label>
</div>
<div style="float:left; ">
<input type="file" name="DeliveryNoteFile" id="DeliveryNote" style="width: 400px;" />
</div>
<div style="float:right; margin-top:10px; margin-left:5px; margin-bottom:0px;">
#(Html.Kendo().Button()
.Name("btnAddAttachment")
.HtmlAttributes( new {type = "submit"} )
.Content("Submit"))
</div>
}
And in JS you need to bind the click function of your submit button like shown below:
$('#btnAddAttachment').bind('click', function () {
$('#attachmentForm').submit();
});
Thanks!

HTML.ActionLink vs Url.Action in ASP.NET Razor

Is there any difference between HTML.ActionLink vs Url.Action or they are just two ways of doing the same thing?
When should I prefer one over the other?
Yes, there is a difference. Html.ActionLink generates an tag whereas Url.Action returns only an url.
For example:
#Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
generates:
link text
and Url.Action("someaction", "somecontroller", new { id = "123" }) generates:
/somecontroller/someaction/123
There is also Html.Action which executes a child controller action.
Html.ActionLink generates an tag automatically.
Url.Action generates only an url.
For example:
#Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)
generates:
link text
and
#Url.Action("actionName", "controllerName", new { id = "<id>" })
generates:
/controllerName/actionName/<id>
Best plus point which I like is using Url.Action(...)
You are creating anchor tag by your own where you can set your own linked text easily even with some other html tag.
<a href="#Url.Action("actionName", "controllerName", new { id = "<id>" })">
<img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />
#Html.DisplayFor(model => model.<SomeModelField>)
</a>
#HTML.ActionLink generates a HTML anchor tag. While #Url.Action generates a URL for you. You can easily understand it by;
// 1. Item Definition
#HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")
// 2. /ControllerName/ActionMethod
#Url.Action("ActionMethod", "ControllerName")
// 3. Item Definition
Item Definition
Both of these approaches are different and it totally depends upon your need.
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm("Index", "Company", FormMethod.Get))
{
<p>
Find by Name: #Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
<input type="button" value="Clear" onclick="location.href='#Url.Action("Index","Company")'"/>
</p>
}
In the above example you can see that If I specifically need a button to do some action, I have to do it with #Url.Action whereas if I just want a link I will use #Html.ActionLink.
The point is when you have to use some element(HTML) with action url is used.
You can easily present Html.ActionLink as a button by using the appropriate CSS style.
For example:
#Html.ActionLink("Save", "ActionMethod", "Controller", new { #class = "btn btn-primary" })
I used the code below to create a Button and it worked for me.
<input type="button" value="PDF" onclick="location.href='#Url.Action("Export","tblOrder")'"/>

Html.ActionLink as a button or an image, not a link

In the latest (RC1) release of ASP.NET MVC, how do I get Html.ActionLink to render as a button or an image instead of a link?
I like to use Url.Action() and Url.Content() like this:
<a href='#Url.Action("MyAction", "MyController")'>
<img src='#Url.Content("~/Content/Images/MyLinkImage.png")' />
</a>
Strictly speaking, the Url.Content is only needed for pathing is not really part of the answer to your question.
Thanks to #BrianLegg for pointing out that this should use the new Razor view syntax. Example has been updated accordingly.
Late response but you could just keep it simple and apply a CSS class to the htmlAttributes object.
<%= Html.ActionLink("Button Name", "Index", null, new { #class="classname" }) %>
and then create a class in your stylesheet
a.classname
{
background: url(../Images/image.gif) no-repeat top left;
display: block;
width: 150px;
height: 150px;
text-indent: -9999px; /* hides the link text */
}
Borrowing from Patrick's answer, I found that I had to do this:
<button onclick="location.href='#Url.Action("Index", "Users")';return false;">Cancel</button>
to avoid calling the form's post method.
Call me simplistic, but I just do:
<a href="<%: Url.Action("ActionName", "ControllerName") %>">
<button>Button Text</button>
</a>
And you just take care of the hyperlink highlight. Our users love it :)
Using bootstrap this is the shortest and cleanest approach to create a link to a controller action that appears as a dynamic button:
Click Me
Or to use Html helpers:
#Html.ActionLink("Click Me", "Action", "Controller", new { #class = "btn btn-primary" })
if you don't want to use a link, use button. you can add image to button as well:
<button type="button" onclick="location.href='#Url.Action("Create", "Company")'" >
Create New
<img alt="New" title="New" src="~/Images/Button/plus.png">
</button>
type="button" performs your action instead of submitting form.
Just simply :
<button onclick="#Url.Action("index", "Family", new {familyid = Model.FamilyID })">Cancel</button>
A late answer but this is how I make my ActionLink into a button. We're using Bootstrap in our project as it makes it convenient. Never mind the #T since its only an translator we're using.
#Html.Actionlink("Some_button_text", "ActionMethod", "Controller", "Optional parameter", "html_code_you_want_to_apply_to_the_actionlink");
The above gives a link like this and it looks as the picture below:
localhost:XXXXX/Firms/AddAffiliation/F0500
In my view:
#using (Html.BeginForm())
{
<div class="section-header">
<div class="title">
#T("Admin.Users.Users")
</div>
<div class="addAffiliation">
<p />
#Html.ActionLink("" + #T("Admin.Users.AddAffiliation"), "AddAffiliation", "Firms", new { id = (string)#WorkContext.CurrentFirm.ExternalId }, new { #class="btn btn-primary" })
</div>
</div>
}
Hope this helps somebody
You can't do this with Html.ActionLink. You should use Url.RouteUrl and use the URL to construct the element you want.
A simple way to do make your Html.ActionLink into a button (as long as you have BootStrap plugged in - which you probably have) is like this:
#Html.ActionLink("Button text", "ActionName", "ControllerName", new { #class = "btn btn-primary" })
<button onclick="location.href='#Url.Action("NewCustomer", "Customers")'">Checkout >></button>
Even later response, but I just ran into a similar issue and ended up writing my own Image link HtmlHelper extension.
You can find an implementation of it on my blog in the link above.
Just added in case someone is hunting down an implementation.
<li><i class='fa fa-user'></i><span>Users View</span></li>
To display an icon with the link
Do what Mehrdad says - or use the url helper from an HtmlHelper extension method like Stephen Walther describes here and make your own extension method which can be used to render all of your links.
Then it will be easy to render all links as buttons/anchors or whichever you prefer - and, most importantly, you can change your mind later when you find out that you actually prefer some other way of making your links.
you can create your own extension method
take look at my implementation
public static class HtmlHelperExtensions
{
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt, object htmlAttributesForAnchor, object htmlAttributesForImage)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
imgBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForImage));
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", action != null ? url.Action(action, routeValues) : "#");
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
anchorBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributesForAnchor));
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
}
then use it in your view take look at my call
#Html.ActionImage(null, null, "../../Content/img/Button-Delete-icon.png", Resource_en.Delete,
new{//htmlAttributesForAnchor
href = "#",
data_toggle = "modal",
data_target = "#confirm-delete",
data_id = user.ID,
data_name = user.Name,
data_usertype = user.UserTypeID
}, new{ style = "margin-top: 24px"}//htmlAttributesForImage
)
For Material Design Lite and MVC:
<a class="mdl-navigation__link" href='#Url.Action("MyAction", "MyController")'>Link Name</a>
#using (Html.BeginForm("DeleteMember", "Member", new { id = Model.MemberID }))
{
<input type="submit" value="Delete Member" onclick = "return confirm('Are you sure you want to delete the member?');" />
}
There seems to be lots of solutions on how to created a link that displays as an image, but none that make it appear to be a button.
There is only good way that I have found to do this. Its a little bit hacky, but it works.
What you have to do is create a button and a separate action link. Make the action link invisible using css. When you click on the button, it can fire the click event of the action link.
<input type="button" value="Search" onclick="Search()" />
#Ajax.ActionLink("Search", "ActionName", null, new AjaxOptions {}, new { id = "SearchLink", style="display:none;" })
function Search(){
$("#SearchLink").click();
}
It may be a pain in the butt to do this every time you add a link that needs to look like a button, but it does accomplish the desired result.
use FORMACTION
<input type="submit" value="Delete" formaction="#Url.Action("Delete", new { id = Model.Id })" />
Just found this extension to do it - simple and effective.
The way I have done it is to have the actionLink and the image seperately.
Set the actionlink image as hidden
and then added a jQuery trigger call. This is more of a workaround.
'<%= Html.ActionLink("Button Name", "Index", null, new { #class="yourclassname" }) %>'
<img id="yourImage" src="myImage.jpg" />
Trigger example:
$("#yourImage").click(function () {
$('.yourclassname').trigger('click');
});
Url.Action() will get you the bare URL for most overloads of Html.ActionLink, but I think that the URL-from-lambda functionality is only available through Html.ActionLink so far. Hopefully they'll add a similar overload to Url.Action at some point.
This is how I did it without scripting:
#using (Html.BeginForm("Action", "Controller", FormMethod.Get))
{
<button type="submit"
class="btn btn-default"
title="Action description">Button Label</button>
}
Same, but with parameter and confirmation dialog:
#using (Html.BeginForm("Action", "Controller",
new { paramName = paramValue },
FormMethod.Get,
new { onsubmit = "return confirm('Are you sure?');" }))
{
<button type="submit"
class="btn btn-default"
title="Action description">Button Label</button>
}

Resources