MVC Button element with parameters - c#

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})';
});

Related

Post form with only input buttons passing parameters to Action in ASP.NET Core

Im working on my thesis work, im making a simple browser game, so far I have a form with 3 buttons that I want to invoke the same action with diffirent parameters this is what i've figured so far:
#using (Html.BeginForm("Gather", "Character", FormMethod.Post, new { #class = "btn-group-vertical mr-2", #role = "group", }))
{
<h3>Woods:</h3>
<input type="submit" class="btn btn-secondary" value="Woods of Deloria (90%)" />
#Html.Hidden("area", "woods")
#Html.Hidden("type", "deloria")
<input type="submit" class="btn btn-secondary" value="Woods of Forgotten souls (50%)" />
#Html.Hidden("area", "woods")
#Html.Hidden("type", "forgotten souls")
<input type="submit" class="btn btn-secondary" value="Shadowforest (10%)" />
#Html.Hidden("area", "woods")
#Html.Hidden("type", "shadowforest")
}
My question is how do i make the diffirent buttons to pass diffirent types, all buttons have to be in same form otherwise it breaks my css. I am using hidden, since I don't want the user to be able to edit the values that are passed as parameters, also I don't want to values to be passed onto the URL.
EDIT: I realized that #Html.Hidden doesn't hide it from the html, what would my approach be if i want to pass parameters to an action from a button, that the user can't edit?
EDIT 2: Alright so i made some progress, changed the form to
<form method="post" class="btn-group-vertical mr-2" role="group">
<h3>Woods:</h3>
<input type="submit" class="btn btn-secondary" name="deloria" value="Woods of Deloria (90%)" />
<input type="submit" class="btn btn-secondary" name="forgotten souls" value="Woods of Forgotten souls (50%)" />
<input type="submit" class="btn btn-secondary" name="shadowforest" value="Shadowforest (10%)" />
</form>
And my post action looks like this:
[HttpPost]
public IActionResult Gather(int id)
{
var taskName = "";
if (Request.Form.ContainsKey("deloria"))
{
taskName = "deloria";
}
else if (Request.Form.ContainsKey("forgotten souls"))
{
taskName = "forgotten souls";
}
else if (Request.Form.ContainsKey("shadowforest"))
{
taskName = "shadowforestD";
}
if (string.IsNullOrEmpty(taskName))
{
return Json("uh oh");
}
else
{
return Json(taskName);
}
}
}
I know it's a mess, but i will find a way to make it a little more compact.
I would take a look at the various options outlined here:
http://www.binaryintellect.net/articles/c69d78a3-21d7-416b-9d10-6b812a862778.aspx
If you are using Razor Pages, and not traditional MVC, you should take a look at handler methods:
https://www.learnrazorpages.com/razor-pages/handler-methods

Model from PartialView to Controller returns null

I have a PartialView that recibes a Model ID and then when you click on the link sends the Model ID to the Controller. My problem was that there were 2 ways to send data from View to Controller but just only one worked for me. What's the reason why?
This worked perfectly for me
<a type="button" class="btn btn-primary" asp-controller="Dictionary" asp-action="Edit" asp-route-wordId="#Model"><i class="fas fa-edit"></i></a>
This one didn't work
<a type="button" class="btn btn-success" href="#Url.Action("Edit/" + Model)"><i class="far fa-list-alt"></i></a>
My question is why the last one didn't work and returned null if I am passing the Model ID to the URL
This is my full PartialView that receives a Model ID and works
#model int
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<td style="width:150px">
<div class="btn-group" role="group">
<a type="button" class="btn btn-primary" asp-controller="Dictionary" asp-action="Edit" asp-route-wordId="#Model"><i class="fas fa-edit"></i></a>
</div>
</td>
And this is my Controller Function that recibes the data
public async Task<IActionResult> Edit(int? wordId)
{
if(wordId == null)
{
return NotFound();
}
var word = await _db.Dictionaries.FindAsync(wordId);
if(word == null)
{
return NotFound();
}
return View(word);
}
The Url.Action overload you are using takes in an action name and you are passing something like /Edit/4 to it. You need to use the proper overload of the Url.Action method that allows you to specify route values.
It would look something like the following:
<a type="button" class="btn btn-success" href="#Url.Action("Edit/" + Model)"><i class="far fa-list-alt"></i></a>
to
<a type="button" class="btn btn-success" href="#Url.Action("Edit", new { wordId = Model } )"><i class="far fa-list-alt"></i></a>`
As a side note, your Edit action takes a nullable wordId which doesn't make much sense to me. Generally, if you're editing something then it has already been created and should always have an id. The only case I can think of where this makes sense is if the Edit action actually handles creating data as well as editing data in which case that would be perfectly valid.
To answer your main question, the reason your 1st anchor is working is because the args are correct.
For example:
<a asp-controller="Dictionary" asp-action="Edit" asp-route-wordId="1">Your link</a>
is equivalent to:
That works!
The second will not work because you are misusing Url.Action, the method you are using is this Url.Action("Action")
Url.Action("Edit/" + Model) or Url.Action("Edit/1")
is searching for an action named: "Edit/1", which in your case will not be found.
so in your 2nd not working example
Your Link
is equivalent to:
<a href="null" />
In your case you should be using this in your anchor:
Url.Action("Edit", "Dictionary", new { id = #Model })
is equivalent to
/Dictionary/Edit/1
so:
Your link

Pass arguments to a C# controller method using <button> and jquery

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" })'"

Using ActionLink parameters with button onclick ?

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

How do I run a GET/POST and JSON RESULT on a page?

I have a page that does a JSON result, get and post method in the controller with two submit buttons. One button goes to the Post method only for a redirect, and the other button goes to the JsonResult method(named AddTableData). How do I set this up in my JQuery code?
$('#firstSubmit').click(function() {
$(document).submit(function() {
});
});
$('#secondSubmit').click(function() {
$('#addTable').submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(response) {
...load Table
});
return false;
});
});
<%using (Html.BeginForm("LoadTable", "Home", FormMethod.Post, new { id = "addTable" })) %>
<td><input id="Submit1" type="submit" name="firstSearch" value="Search" /></td>
<td><input id="Submit2" type="submit" name="secondSearch" value="Search" /></td>
How do I use the firstSubmit to hit the post only, and the second submit to work the JsonResult only?
EDIT
$('#secondSubmit').click(function() {
$.getJSON("Home/AddTableData", {Name:"Name on Document"}, function(json) {
alert("good");
});
});
My variables that usually get picked up on a get/post function is gone. How do I post them to my JSon function?
Assuming I am understanding you correctly I have 2 answers for you...
Why use JavaScript just to post a form without Ajax?
If you must post the form using JavaScript, submit the form, not the document, so something like:
$('form').submit();
$('#firstSubmit').click(function() {
$('#addTable').submit();
});
$('#secondSubmit').click(function() {
$.getJSON("Home/AddTableData", $('#addTable').serialize(), function(json) {
alert("good");
});
});
<%using (Html.BeginForm("LoadTable", "Home", FormMethod.Post, new { id = "addTable" })) %>
<td><input id="Submit1" type="button" name="firstSearch" value="Search" /></td>
<td><input id="Submit2" type="button" name="secondSearch" value="Search" /></td>
I have not tested this:
$('#secondSubmit').click(function() {
$url = 'Home/AddTableData/?'+$('#add_table').children('input').serialize()
$.getJSON($url, {Name:"Name on Document"}, function(json) {
alert("good");
});
});

Categories

Resources