I want to get the information(which is dynamically generated) from one html page into another html page.
I used a tag th:fragment in first html page and th:replace in second html page.
But i am getting only static content of first page, is it possible to get the dynamic data or not? can anyone help me please.
Thanks in advance.
Here is my Java code :
#Controller
public class WelcomeController {
#RequestMapping("/")
public ModelAndView usingToList(Model model) {
List<String> colors = new ArrayList<>();
colors.add("green");
colors.add("yellow");
colors.add("red");
colors.add("blue");
model.addAttribute("message", "harika");
model.addAttribute("colors", colors);
List<String> colors2 = new ArrayList<>();
colors2.add("pinkish");
colors2.add("green");
colors2.add("yellow");
colors2.add("red");
colors2.add("blue");
model.addAttribute("coloring", colors2);
ModelAndView mv = new ModelAndView();
mv.setViewName("welcome");
return mv;
}
#GetMapping("/toList")
public String usingToList2(Model model,String color) {
System.out.println("inside uselist");
List<String> colors2 = new ArrayList<>();
if(color.equals("pinkish"))
{
colors2.add("pinkish");
colors2.add("amity");
colors2.add("pimity");
}
if(color.equals("green"))
{
colors2.add("greenish");
colors2.add("amity");
colors2.add("Pretty");
}
model.addAttribute("colors", colors2);
return "welcome";
}
}
Below is my sample POC :
here is my fragment: nav.html which it load the colors dynamically. I am using this side bar fragment in all the pages. When I go another page, data in the side bar is disappering.
<div th:fragment="sidebar2">
<div class="sidebar-sticky pt-3">
<ul class="nav flex-column" id="accordionSidebar">
<li class="nav-item">
<a type="button"
id="collapse"
data-toggle="collapse"
data-target="#collapseExample"
aria-expanded="false" aria-
controls="collapseExample">
<span class="menu-title">Colors List</span>
<span data-feather="plus-circle"></span>
</a>
<div class="collapse" id="collapseExample">
<ul class="nav flex-column sub-menu"
id="collapseExample2">
<li th:each="color :
${coloring}">
<a th:href="#{/toList(color=${color})}"
th:text="${color}"> ></a>
</li>
</ul>
</div>
</div>
welcome.html:
<div th:replace="fragments/nav :: sidebar2"></div>
<main role="main" class="container">
<div class="starter-template">
<h1>Spring Boot Web Thymeleaf Example</h1>
<h2>
<span th:text="'Hello, ' + ${message}"></span>
</h2>
</div>
<ol>
<li th:each="color2 : ${colors}" th:text="${color2}"></li>
</ol>
</main>
When you navigate from one page to another, the Model is empty again (unless you are doing a <form> POST).
When you show the welcome.html Thymeleaf template via usingToList2(), then there is nothing in the Model for the coloring key.
To solve it, also add the coloring key in the usingToList2() controller method.
UPDATE: If all controllers need it, you can use #ControllerAdvice:
#ControllerAdvice
public class GlobalControllerAdvice {
#ModelAttribute("coloring")
public List<String> coloring() {
List<String> colors2 = new ArrayList<>();
colors2.add("pinkish");
colors2.add("green");
colors2.add("yellow");
colors2.add("red");
colors2.add("blue");
}
}
Or if all methods in a single controller need it, you can just add that method in the controller class itself.
My problem is when i'm trying to get the best 4 posts who's match the same author name , as you see in the following image :
this is the controller :
Controller Code
and here is the view :
View code
so how i can call the controller method from the view , what's the code will looks like ? and thanks ..
also here is the controller method :
public ActionResult SameAuthor(string author)
{
var result = db.Books.Where(b => b.Author_name == author).Take(4).ToList();
return View(result);
}
and the view code (book page , the following code is a part of book page , that show the book details and info , so this code for show under the post details the most 4 post for same author) is :
//DISPLAYING 4 BOOKS FOR SAME AUTHOR
<div class="well">
<div class="row">
#foreach (var item in Model)
{
<div class="col-sm-6 col-md-3">
<div class="thumbnail">
<img src="/Books/RetrieveImage/#item.Book_id" alt="Generic placeholder thumbnail">
</div>
<div class="caption">
<h3>#item.Book_name</h3>
<p>Some sample text. Some sample text.</p>
<p>
<a href="#" class="btn btn-primary" role="button">
Button
</a>
<a href="#" class="btn btn-default" role="button">
Button
</a>
</p>
</div>
</div>
}
</div>
</div>
and thanks
If you are trying to show the result of your SameAuthor action method inside another view, you may use Html.Action helper method to do so.
So in your some other razor view, you can include the below line
#Html.Action("SameAuthor","Book",new {author="Author name here"})
After some research, I could not find a good answer form my question.
I have a helper method to create an action link with a "+" sign and a label:
public static HtmlString NewButton(this IHtmlHelper htmlHelper)
{
var htmlAttributes = new { #class = "btn btn-small btn-primary" };
return htmlHelper.ActionLink("Insert", "Create", null, new RouteValueDictionary(), htmlAttributes);
}
How can I include the "+" sign in a way that my final html looks like this?
<a href="/posts/new" class="btn btn-small btn-primary">
<i class="ace-icon fa fa-plus"></i>
Insert
</a>
In my page, I use my helper like this:
<div class="form-actions">
#Html.NewButton()
</div>
The only way I found was passing the "Url" object to my method, like this:
public static HtmlString NewButton(this IHtmlHelper htmlHelper, IUrlHelper url)
{
var link = url.Action("Create");
var el = string.Format("<a href = \"{0}\" class='btn btn-small btn-primary'><i class='ace-icon fa fa-plus'></i>Insert</a>", link);
return new HtmlString(el);
}
In my view, I use it this way:
#Html.NewButton(Url)
I´m not using ActionLink at all
You can't, per se. However, nothing says you have to use Html.ActionLink. Simply, use Url.Action, instead, and then build your tag manually:
<a href="#Url.Action("Insert", "Create")" class="btn btn-small btn-primary">
<i class="ace-icon fa fa-plus"></i>
Insert
</a>
I am trying to make look #Html.Actionlink as button.
Working Html.Actionlink:
<li class="btn btn-sm"> #Html.ActionLink("Redeem Reward", "GetReward",
"Home", new { id = price.PriceId }, new { #class = "lnkGetReward"})</li>
Currently when I click it looks like as if a link is clicked, apart from the text if we click the button border it doesn't work.
I am also using font awesome classes.
Can I use #Url.Action instead with same id and #class?
Instead of having your button classes on the li apply them directly to the link.
As you are using bootstrap you might want to add btn-default to get the full style of the button.
<li>
#Html.ActionLink("Redeem Reward", "GetReward", "Home",
new { id = price.PriceId },
new { #class = "lnkGetReward btn btn-default btn-sm"})
</li>
However if you are 100% sure you want to use Url.Action your code would look like the following.
<li class="btn btn-sm">
Redeem Reward
</li>
Again I would suggest that you apply the btn btn-sm directly to the link. Possibly with a btn-default.
Edit based on comment:
<li>
<a href="#Url.Action("GetReward", "Home", new { id = price.PriceId })" class="lnkGetReward btn btn-default btn-sm">
<i class="fa fa-mobile"></i> Redeem Reward
</a>
</li>
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>
}