Straight forword I think just can't find the syntax...
I have an ActionLink which uses an id property,
<td style="padding-right:35px">#Html.ActionLink("Edit", "EditUser", new { #id = user.ID.ToString("N") }, new { #class = "btn yellow"})</td>
Basically I want to change this to a btn, but I am not sure how to pass the id parameter , I think it's something like this....
<button type="button" class="btn blue" id="user.ID.ToString("N")" onclick="location.href='ReferralTarget/EditUser'"><i class="icon-edit"> Edit</button>
Where ReferralTarget is my control and EditUser my actionResult..
Please note this is an ASP.NET MVC4 application using Razor2 views...
Try something like this:
<button type="button" class="btn blue" onclick="location.href='#Url.Action("EditUser", "ReferralTarget", new { #id = user.ID }'"><i class="icon-edit"> Edit</button>
You could also do something like this if you like the jquery route:
#functions
{
private string GetUserId()
{
//I'm not sure where you are getting user from, but if it's from the model,
//you would need to change this to something like #Model.something....
return user.ID;
}
}
<script type="text/javascript">
$(document).ready(function() {
$('#edit').click(function() {
location.href = "ReferralTarget/EditUser/" + "#GetUserId()";
});
});
</script>
<input type="button" id="edit" value="edit" />
There is an easy trick-
Use jqueryUi, and justdo $("#linkid").button(), and style it how ever u want
Related
In my View i have the following code:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
Download
In my Control i have de following code:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
In this particular case, i want to pass the createdDate value that is inside the textbox (createdDate) to my Url.Action(...), so it could be passed as a queryString in my URL.
This action is invoked as a GET request, and in GetRoomAccessHistory control method, i should get my createdDate.
Thank you.
PS
I think the solution should be something like this:
<a href="#Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
I have got a possible answer:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
This does exactly what i want and it works, but i was trying to find a more nice solution because my experience in ASP.NET MVC is low.
You're using the wrong tool for the job.
Since the Url.Action() helper runs on the server-side, it has already executed when the page was first loaded, and generated a fixed URL which is inserted into the page's HTML. It cannot know what the user later enters into the textbox.
If you want to capture data which a user has entered, it makes more sense to use a form. In this case I've used the BeginForm tag helper to generate a suitable HTML <form> tag:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
When submitted, this will generate a GET request to the GetRoomAccessHistory action's URL, and append createdDate as a querystring variable, using the value from the textbox.
For Get request,try to use window.location.href.
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
And your solution could be simplified to
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>
I have a bootstrap modal which has many buttons which help to download files of different formats. I am able to enter the controller method when I use the set the onclick function as below:
onclick="location.href='#Url.Action("DownloadAsJPG", "Home")'"
I would like to do some condition based file downloading, based on the button that was pressed and hence I was thinking of passing a parameter as done here and here by setting the value attribute of the buttons
HTML :
<button type="button" id="tojpg" class="btn btn-outline-primary" value="jpg">JPG</button>
<button type="button" class="btn btn-outline-primary" value="jpgcmyk">JPG-CMYK</button>
<button type="button" class="btn btn-outline-primary" value="jpgrgb">JPG-RGB</button>
The argument in the controller method always remains null. I'm not sure what I have missed.
Controller method:
public FileResult DownloadAsJpg(string argument)
{ Some action }
I tried to play with a jquery which I found on a stackoverflow question which doesn't help me either, I couldn't reach the controller using this jquery.
Jquery
$('#tojpg').click(function (e) {
e.preventDefault();
window.location = '/Home/DownloadAsJpg?argument=' + $('#tojpg').val();
});
Any tips would be greatly appreciated.
If you can reach your controller with
onclick="location.href='#Url.Action("DownloadAsJPG", "Home")'"
and just want to pass some parameters. You can do that same was as
onclick="location.href='#Url.Action("DownloadAsJPG", "Home", new { argument = "tojpg" })'"
or with help of Jquery event
Edit
Try to wrap your event into $(document).ready(). By my experience, most of the time the reason for not working events is a that your buttons is not yet created when event binding happends.
$(document).ready(function() {
$('#tojpg').click(function (e) {
e.preventDefault();
location.href = '#Url.Action("DownloadAsJPG", "Home", new { argument = "tojpg" })';
});
}
And if you dont want to write a separate event for each button option you can create something like this.
<button type="button" class="btn btn-outline-primary" value="jpg">JPG</button>
<button type="button" class="btn btn-outline-primary" value="jpgcmyk">JPG-CMYK</button>
<button type="button" class="btn btn-outline-primary" value="jpgrgb">JPG-RGB</button>
and Jquery event like this
$(document).ready(function() {
$('.btn').click(function () {
location.href = '#Url.Action("DownloadAsJPG", "Home", new { argument = "'+ $(this).attr("value") +'" })';
});
}
That should work.
There are two ways of solving this:
Option 1
A <button /> is not part of the data that the form is posting. That is why it doesn't turn up at the server side. You should change this into an input like so:
<input type="submit" name="argument" value="jpg" />
The name of this field should be the same one as the name of the parameter in your action. Because this is an input-field, the browser will send the it with the entire post. This is what is being done in the posts you referred to.
Option 2
If you want to use window.location instead, then you need to make sure the action allows for a GET-request and that you pass in argument as the querystring:
onclick="location.href='#Url.Action("DownloadAsJPG", "Home", new { argument = "jpg" })'"
Button I'm using has to have a background-image, but <input type="submit"> can't have a background-image.
For instance, I can use Html.ActionLink with image:
#Html.ActionLink("Add to Cart", "AddCart","Products", new { id = Model.product_id,},new { #class = "**add-cart item_add"** })
class = "add-cart item_add" doesn't work in input
What should I do? Thanks a lot...
Input button of type submit should be stylable; however, you can use <button type="submit" or <input type="image" for image button. For image button, set the src attribute; for button, add a background-image: url("../images/something.png") as an example.
Use a button and on the button's on click event, make a call (ajax if you need) to the server using javascript.
Your code would look smth like this:
<button id="yourBtnName" class="add-cart item_add">Submit</button>
<script>
$('#yourBtnName').click(function(e) {
e.preventDefault();
//do whatever you want to do on the button click event
});
</script>
How do I pass parameters to a controller action method with a button element?
This is not a form submit, I just want a button that is going to take you to another page, but the action method requires parameters.
I currently have:
<button type="button" class="btn btn-info" onclick='window.location = "#Url.Action("Index", "ReviewPendingApprovals", new object[] { Model.QuoteGuid })";'>
However, this results in empty HTML:
<button type="button" class="btn btn-info" onclick='window.location = "";'>
what exactly am I doing wrong here?
It's best to use an HTML helper for this.
#Html.ActionLink(
"ButtonText",
"Index", // controller action
"ReviewPendingApprovals", // controller
new { Model.QuoteGuid }, // action parameters aka route values
new { #class = "btn btn-info" }) // html attributes
RIGHT ANSWER HERE:
You did two things wrong: you didn't mark the onClick delegate as an href, and you didn't map the argument/route values to any parameter (but that didn't cause the render HTML markup to be blank)
I prefer to use input tags, but you can use a button tag
Here's what your solution should look like using HTML:
< input type="button" class="btn btn-info" onclick='window.location.**href** = "#Url.Action("Index", "ReviewPendingApprovals", new { **someParamHere** = Model.QuoteGuid })";'/>
I never tried to do it directly from a button, but when I use the controller to do it, it looks something like:
return RedirectToAction("ActionName", new { param1 = param1_value, param2 = param2_value });
so I suggest you try this:
<button type="button" class="btn btn-info" onclick='window.location = "#Url.Action("Index", "ReviewPendingApprovals", new object[] { object_name = Model.QuoteGuid })";'>
Try adding the URL Scheme parameter to Url.Action:
<button type="button" class="btn btn-info" onclick='window.location = "#Url.Action("Index", "ReviewPendingApprovals", new object[] { Model.QuoteGuid }, this.Request.Url.Scheme)";'>
You could code like this:
$('.btn-info').click(function (e) {
var url='#Url.Action("Index", "ReviewPendingApprovals",new { id= Model.QuoteGuid })';
window.location=url;
});
Use Jquery instead of onclick event:
$('button').click(function(){
winodw.location.href = '#Url.Action("Action","Controller",new{parameter name = value})';
});
I have been following the answers on here but can't seem to get it to work. I think it's firing my function and calling my controller but it isn't rendering my partial view. Any help would be awesome.
Controller
public ActionResult Detail(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User_Accounts user_accounts = db.User_Accounts.Find(id);
if (user_accounts == null)
{
return HttpNotFound();
}
return PartialView("_Detail", user_accounts);
}
HTML
<h2>Index</h2>
<div class="container left">
<div class="panel-default panelbox" style="position:static">
#*<p>
#Html.ActionLink("Create New", "Create")*#
#using (Html.BeginForm("Index", "Users", FormMethod.Get))
{
<p>
Type: #Html.DropDownList("userType", "All")
</p>
<p>
Last Name: #Html.TextBox("SearchString")
</p>
}
</div>
<div class="panel panel-default left">
<div class="panel-heading">
<label style="text-align:center">
User
</label>
</div>
<div class="table-responsive">
<table id="UserTable" class="table-bordered table leftPanel table-condensed">
#foreach (var item in Model)
{
<tr>
<td>
<button data-url='#Html.Action("Detail", "Users", new { id = item.user_id_IN })' id="js-reload-details">#Html.DisplayFor(modelItem => item.DisplayName)</button>
#*#Html.ActionLink(item.DisplayName, "Detail", new { id = item.user_id_IN }, new { onclick = "renderPartial();" })*#
</td>
</tr>
}
</table>
</div>
</div>
</div>
<div>
<label>Details</label>
<div id="detailsDiv"></div>
</div>
Script
<script>
$('.js-reload-details').click(function (evt) {
var $detailDiv = $('#detailsDiv'),
url = $(this).data('url');
$.get(url, function (data) {
$detailsDiv.replaceWith(data);
});
});
</script>
Let me know if you need anything else.
You cant use data-url='#Html.Action("Detail", "Users", new { id = item.user_id_IN })' in your button to generate a url. #Html.Action() is a method which calls you controller. What would be happening is that for each item in your model you would be hitting the Detail method of UsersController (performance must of been awful if you had a lot of items :) ).
Since you appear to need only the one url (/Users/Detail) I suggest you just store the ID in data to minimize the html generated. As noted in the other answers you also need to use a class name for the button to prevent invalid html, and I also suggest using type="button" because the default (depending on the browser) may be "submit" (you don't have a form so does not matter in this case, but its good practice to get into). There is also no real need to use #Html.DisplayFor() unless your using a custom DisplayTemplate or have a [DisplayFormat] attribute on the property.
Change the html to
<button type="button" data-id="#item.user_id_IN" class="js-reload-details">#item.DisplayName</button>
and the script to
var url = '#Url.Action("Detail", "Users");
$('.js-reload-details').click(function() {
$.get(url, { id: $(this).data('id') }, function (data) {
$('#detailsDiv').html(data);
});
});
Note you do not want to use replaceWith() in your case. .replaceWith() would replace the actual div <div id="detailsDiv"></div> with the html your method returned, so the next time a user clicked on this or any other button, the method would be called, but <div id="detailsDiv"></div> no longer exists and nothing would happen.
$('#detailsDiv').html('Hello world');
renders
<div id="detailsDiv">Hello world</div>
but
$('#detailsDiv').replaceWith('Hello world');
renders
Hello world
The id of your button id="js-reload-details"
Mistake this code is repeated in a foreach loop. which will cause multiple id's of the same name on your HTML page.
Your click event is on : '.js-reload-details'. which is a class:
so make your code like this:
#foreach (var item in Model)
{
<tr>
<td>
<button data-url='#Html.Action("Detail", "Users", new { id = item.user_id_IN })' class="js-reload-details">
#Html.DisplayFor(modelItem => item.DisplayName)
</button>
</td>
</tr>
}
One error I noticed in your jQuery is that you have $detailsDiv.replaceWith(data);
It should be $detailDiv according to your code: var detailDiv = $('#detailsDiv'); instead of $detailsDiv
<script>
$(document).ready(function(){
$('.js-reload-details').click(function (evt) {
evt.stopPropagation();
var detailDiv = $('#detailsDiv');
// TRY using the attr function:
var url = $(this).attr("data-url");
$.get(url, function (data) {
detailDiv.html(data);
});
});
});
</script>
UPDATE:
<script>
$(document).ready(function(){
$('.js-reload-details').click(function (evt) {
evt.stopPropagation();
var detailDiv = $('#detailsDiv');
// TRY using the attr function:
var url = $(this).attr("data-url");
$.get(url).success(function(result) {
detailDiv.html(result);
});
});
</script>
It's a good practice we use unique id's for our HTML elements. Since the following statement is going to be executed mulitple times
<button data-url='#Html.Action("Detail", "Users", new { id = item.user_id_IN })' id="js-reload-details">#Html.DisplayFor(modelItem => item.DisplayName)</button>
You will have multiple buttons with the same id. Instead of doing so, you could use a class.
<button data-url='#Html.Action("Detail", "Users", new { id = item.user_id_IN })' #class="js-reload-details">#Html.DisplayFor(modelItem => item.DisplayName)</button>
Then you have to correct your script:
// Now we bound the click event in all the elements that contain
// the .js-reload-details class
$('.js-reload-details').click(function (evt) {
var $detailDiv = $('#detailsDiv');
// Here was your the error
var url = $(this).attr("data-url");
$.get(url, function (data) {
$detailsDiv.replaceWith(data);
});
});