mvc3 Html.ActionLink as image not as text - asp.net-mvc-3

<div class="orderby_name">
#Html.ActionLink(" ", "DisplayCategory", "Categories", new { articleSortBy = "Name", articleSortType = "asc" }, null)
</div>
i am lookin in razor if exist ImageLink. Now i have #Html.ActionLink and becouse i do not have any text name i can not click on it. I want to have image as link.
How can i make image as link in razor?

The built-in helper cannot do that.
You need to create an ordinary <a href="#Url.Action(...)"> tag.

Hope this code is helpful
#using (Html.BeginForm())
{
<a href='#Url.Action("Index")'>
<img src='#Url.Content("../../Content/Images/head.jpg")' alt="Home Page">
</a> }

Actually it looks like there is a way.. if you add a CSS rule to the htmlAttributes, as is shown in the top answer of this post:
Html.ActionLink as a button or an image, not a link

In asp.net mvc 3 the code you have works with the single space for the link text, just add a class name that points to an image (the class name below points to a font awesome image):
#Html.ActionLink(" ", "ActionName", "ControllerName",
new {UniqueId = item.UniqueId},
new { #class = "fa fa-download", #title = "Download the document" })
And add some css to prevent the image from having an underline:
a.fa
{
text-decoration:none;
}

Related

How to use Ajax to update RenderBody() section with VS 2012 Internet Template?

I've looked at few examples where Ajax can be used to update divs or other elements with ids. I have not been able to find an example that uses Ajax with Razor views to help me with the following.
My page is a standard Menu at the top, body in the middle, and a footer. There is no real need to update the header and footer each time. In fact, my page only requires a section of the Body to be updated based on menu clicks and actionlinks on the page. I'm testing this with the Internet Template that is created using VS 2012 if that helps such that I do not have to clutter this request with a bunch of code snippets. I am using Razor views and C# for coding preferences.
So, given the default _Layout.cshtml file, how would I load the About page i.e. RenderBody() section via Ajax? I've tried adding Ajax.BeginForm(...) to my _Layout.cshtml file around one div with an UpdateTargetId that matches a div that I wrapped around the RenderBody() call, returned a partial view from my controller, but that's not quite right. What I get is my partial view only. (The About page with no menu, footer, etc. just the code on the About page)
Would someone kindly share a link that demonstrates this functionality or kindly share the code that does what I desire i.e. swap index view with about view without a full page refresh? Some explanation of what I'm missing would be nice, but I'm sure I could deduce from a solid example where I went awry. As always, your time is much appreciated.
EDIT: Using Jasen's suggestion
_Layout.cshtml
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Ajax.ActionLink("About", "About", "Home", null, new AjaxOptions { HttpMethod = "get", UpdateTargetId = "body" }, new { })</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</nav>
....
Inside my div id="body"
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
.....
HomeController.cs
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return PartialView();
}
......
Here is a simple example with jquery. The About partial gets injected into the div with id="body".
<button>About</button>
<div id="body"></div>
$(function () {
$("button").on("click", function(e) {
$.get("Home/About").done(function(result) {
$("#body").html(result);
});
});
));
Controller Action
[HttpGet]
public ActionResult About()
{
return PartialView("About");
}
About.cshtml
#{ Layout = null }
<h2>Home/About</h2>
<p>Blah... </p>
Edit: Maybe a better example is to use a link instead
#Html.ActionLink("About", "About", "Home", null, new { #class="menu-button" })
<div id="body"></div>
$(function () {
$(".menu-button").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
$.get(url).done(function(result) {
$("#body").html(result);
});
});
});
Edit: Without jquery you want to use Ajax.ActionLink() instead of Ajax.BeginForm()
#Ajax.ActionLink("About", "About", "Home", null, new AjaxOptions { HttpMethod = "get", UpdateTargetId = "body" }, new { })
<div id="body"></div>
In your HomeController.cs
public PartialViewResult About()
{
ViewBag.Message = "Your app description page.";
return PartialView();
}
In your _Layout.cshtml do not forget to import:
<script src="~/Content/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="~/Content/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

Need to show / hide a div on clicking on a link

I'd like to do something like this fiddle only this works on buttons instead of links:
http://jsfiddle.net/qNhZj/
I need it to work on links and also i have an intro div which gets hidden after clicking on one of the links.
Can anyone help me out please.
You just have to declare link instead of input.
In the class list, add the id of the div you want to show.
Click a button to make it visible:
<div id="intro-tekst">Intro text here !</div>
<div class="boxes" id="coke">Coke is awesome!</div>
<div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>
<div class="boxes" id="milk">Milk is healthy!</div>
<br />
<p>
I change my mind:
<ul>
<li>Coke</li>
<li>Bubble Tea</li>
<li>Milk</li>
</ul>
</p>
And bind it like this :
$(document).ready(function() {
var url = window.location.href;
var option = url.match(/option=(.*)/);
if (option !== null) {
$(".link ." . option[1]).trigger('click');
}
$(".link").bind('click', function () {
$('#intro-tekst').hide();
$('.boxes').hide();
$('.link').removeClass('selected');
$(this).removeClass('link');
$('#' + $(this).prop('class')).show();
$(this).addClass('link selected');
});
});
JsFiddle code here : http://jsfiddle.net/Pq5Cv/8/

ActionButton instead of ActionLink

I want to create a button which when clicked calls an action. I have used Html.ActionLink to create a link which does exactly that but there is no Html.ActionButton. Is there some other way?
Here is an example using Bootstrap's CSS button and applying it against the link to make it look exactly like the button.
#Html.ActionLink("Select", "Select", new { id = patient.Id }, new { #class = "btn btn-primary", #style = "color:white" })
Is there some other way?
You could use a html <form>:
#using (Html.BeginForm("someAction", "someController"))
{
<button type="submit">OK</button>
}
This seems very simple - am I missing something?
#Html.ActionLink("About", "About","Home", new { #class = "btn btn-success" })
Use this:
#using (Html.BeginForm("yourAction", "yourController"))
{
<input type="submit" value="Some text"/>
}
#using (Html.BeginForm("ActionName", "ControllerName")){
<input type="button" value="Submit" />
}
a[type="button"] {
background-color: #d3dce0;
border: 1px solid #787878;
cursor: pointer;
font-size: 1.2em;
font-weight: 600;
padding: 7px;
margin-right: 8px;
width: auto;
text-decoration: none;
}
#Html.ActionLink("ActionName", "ControllerName",null, new {type = "button" })
Sometimes your button might have nested markup (e.g. for an icon)
This might be helpful to some people:
<button type="button" onclick="location.href='#Url.Action("Action", "Controller")'" class="btn btn-success">My button name <i class="glyphicon glyphicon-search"></i></button>
type=button is required to prevent page from submitting... Another possible solution (if you think type=button looks weird because the element is already a button) would be to call event.preventDefault() in the OnClick javascript handler.
<button onclick="event.preventDefault(); location.href='#Url.Action("Action", "Controller")'" class="btn btn-success">My button name <i class="glyphicon glyphicon-search"></i></button>
This should answer your question.
Can I use an asp:Button like an Html.ActionLink?
Uses CSS to make the link look like a button.
Or use the button inside the form with the form controls moving the page along.
You can write a link to controller and view this way / skip the whole razor notation (worked for me recently on my localhost!):
<button type="submit">OK</button>
use FORMACTION
<input type="submit" value="Delete" id="delete" formaction="#Url.Action("Delete", new { id = Model.Id })" />
I know this is an old topic, but this helped me:
#Html.ActionLink("New member", "Create", null, new {#class = "btn btn-default"})
Make sure you use the correct overload or else you will be directed to the wrong controller.
you need to use a "null" before the new {} as shown below:
#Html.ActionLink("About", "Action Name","Controller Name",null, new { #class = "btn btn-success" })
Notice the null above. This is important!!!
For those of you trying to make an anchor tag look like a button in Bootstrap v3 (maybe v4, too), beware that there are some subtle styling differences regarding margin that bootstrap targets to the Input element and not the A element. This can be a little frustrating when trying to put several buttons next to each other.
There's a rather obvious reason why MVC doesn't have a ButtonLink helper: Think about it. Buttons do not link to anything. They run code. So what code would the helper render? I mean it seems simple that it could just render something like onclick="window.location=/controller/method..." but, is that really what you want? Is it what everyone always wants? Isn't that really just doing a GET? It gets kind of goofy.
So, really, if you want a button that opens a link the easiest way is to do what everyone else suggested and style an A tag to look like a button but then probably go into your stylesheet and do a very specific target of your button anchors to get the same styling as actual buttons. Or use an Input tag and force Razor (or whatever) to render the link inline with your JavaScript.

MVC 3 Update uploaded image with same name

I'm stumped on an image issue... heres the lowdown.
In my layout i have an image that acts as a logo... however in the admin view there is the ability to upload a new logo and it simply replaces the current one with the exact same name. After the postback the image does not change on the layout to the updated image even though the updated image is saved. If I refresh the page with ctrl and F5, cache is gone and I can see the new image but I need it to be more automated.
Heres my img tag in the layout
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")" id="ClientLogo" alt="" width="227" height="130" style="float: left;" />
Heres the admin View
#using (Html.BeginForm("Admin", "Home", FormMethod.Post, new { #encType = "multipart/form-data" }))
{
<fieldset>
<legend>Logo Management</legend>
<p>
<input type="file" name="FileUpload" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</fieldset>
}
And finally the action
[Authorize]
[HttpPost]
public ActionResult Admin()
try
{
HttpPostedFileBase file = Request.Files[0];
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/themes/base/images"), fileName);
file.SaveAs(path);
System.IO.File.Delete(Path.Combine(Server.MapPath("~/Content/themes/base/images"), "Client_Logo.jpg"));
System.IO.File.Move(Path.Combine(Server.MapPath("~/Content/themes/base/images"), fileName), Path.Combine(Server.MapPath("~/Content/themes/base/images"), "Client_Logo.jpg"));
}
else
{
ModelState.AddModelError("uploadError", "There is a problem uploading the file.");
}
}
catch (Exception e)
{
ModelState.AddModelError("uploadError", e);
}
return View();
What does everyone suggest to do in order to refresh the image in the layout when the view is returned after uploading the image?
Cheers.
The quickest fix I can think of is displaying your logo with something random so the client would never hit the cache like:
"/images/yourlogo.png?version=123455634"
Replacing 123455634 with something always random.
Since the url of your picture will never be the same, the picture will always be downloaded.
You can mess with the cache headers for this particular file but this is the quickest fix I can think of.
Hope this helps.
EDIT try this:
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg?version=" + DateTime.Now.Ticks.ToString())" id="ClientLogo" alt="" width="227" height="130" style="float: left;" />
Well, you could set caching headers on that file NOT to cache in your web.config but that isn't ideal.
How about some jQuery?
In your Layout:
<img src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")" id="ClientLogo" alt="" width="227" height="130" style="float: left;" data-src="#Url.Content("~/Content/themes/base/images/Client_Logo.jpg")"/>
In your view that you want to change the image:
<script type="text/javascript">
$(function(){
$('#ClientLogo').attr('src',$('#ClientLogo').data('src') + '?t=' + new Date().getTime());
});
</script>

How to add data-autocomplete HTML attribute to TextBoxFor HTML helper?

autocomplete text box for getting city autocomplete textbox.
My code look like this,
<input id="location" type="text" name="q"
data-autocomplete="#Url.Action("locationSearch", "Home",
new { text = "location" })"/>
Now i want to convert this to razor syntex. I tried this but not working.
#Html.TextBoxFor(model => model.Location,
new { data-autocomplete = Url.Action("locationSearch", "Home")})
How can i solve this??
data-autocomplete is an HTML attribute. First of all you can't use dashes when specifying attributes in MVC, therefore you need to replace your data-autocomplete with data_autocomplete. MVC is "smart enough" and final result will read data-autocomplete.
To add an HTML attribute to your text input you need to use the following HTML helper:
#Html.TextBoxFor(model => model.Location, new { data_autocomplete = Url.Action("locationSearch", "Home") })
Please work on your acceptance rate.
u can just use this
in your view
<select id="location" name="location"></select>
<input type="submit" value="Send">
that is actually dropdownlist, not textbox, they edit the layout via css
You should use undescore symbol in HtmlAttributes argument:
#Html.TextBoxFor(model => model.Location, new { data_autocomplete = Url.Action("locationSearch", "Home")})

Resources