I want to change the following variable to false using the onclick method of a button in my shared navbar.
Variable
public static bool LoginStatus { get; set; } = true;
What I have so far which does not work:
Html button
<button type="button" class="btn btn-primary" onclick=#Apex_Leaderboard_Website.Models.LoginViewModel.LoginStatus = false>Log Out</button>
I have tried a form but with the button in the shared navbar it makes it difficult to submit it to the appropriate handler.
you should use asp:Button because you want to modify a C# class property. then you can OnClick event on it so that you will be able to call a backend(code-behind) method and in that method, you can set the enter code here to false.
Here is the reference for you.
You can use posting a form or use js.
<form method="post" asp-route-LoginStatus=false>
<input type="submit" value="Log Out" />
</form>
js:
<button type="button" class="btn btn-primary" onclick="passData()">Log Out</button>
function passData() {
$.ajax({
type: "POST",
url: "xxx",
data: { LoginStatus: false },
success: function(data) {
}
});
}
action:
public ActionResult xxx(bool LoginStatus)
{
....
}
Related
So I have a like button in my index view which looks like this. It calls the function "PostLike" which increases the number of likes by inserting a new row in my "like" table.
<form asp-action="PostLike" asp-route-id="#item.Id">
<input id="btn" type="submit" value="Like" class="btn btn-primary">
</form>
What I want to do is to change the value of the button from like to unlike when it's clicked, without refreshing the page and keeping the value after refreshing the app. Any ideas? I know I have to use some AJAX function for this to work, but I don't know how it should be implemented.
you can make an ajax call to check the success or error request status then change the value on the success method
ArticleLikeObj is the object to be sent to the controller to save like article action and it’s a view model class containing properties like ArticleId and current logged user
ajax call
<input id="#item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">
<input id="#item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">
<input id="#item.ArticleId" onClick="Submit_clicked(this.id)" value="Like" class="btn btn-primary">
function Submit_clicked(clicked_id)
{
let ArticleLikeObj = {ArticleId:clicked_id, UserName:"Doe"};
SendRequest(ArticleLikeObj);
}
function SendRequest(ArticleLikeObj) {
$.ajax({
type: "POST",
url: '#Url.Action("action name","controller name")',
data: ArticleLikeObj,
contentType: 'application/x-www-form-urlencoded',
dataType: "json",
success: function (response) {
document.getElementById("Submit").value = "Liked";
},
error: function () {
alert("Error!");
}
});
}
I'm working in an ASP.NET MVC app and I want to disable a button when during OnSubmit event of the form, just for prevent double click of the users.
All JQuery part is working fine but I don't understand why, when I disabled the submit button, it always call the default Action of my controller.
Here is the cshtml code:
#using(Html.BeginForm()){
<input type="submit" value="Submit"/>
}
<script>
$(function(){
$("form").submit(e=>{
$('input[type="submit"]').prop("disable",true)
})
})
</script>
The JQuery part works and make the button disabled.
My controller:
public class MyController:Controller{
public ActionResult MyController(ExampleModel model){
return View(model);
}
[HttpPost,ActionName("MyController")]
public ActionResult FormSubmmit(ExampleModel model){
//Do some checks
return View(model);
}
}
The case is that if I make the button disabled, the form always call the action 'MyController' instead of the action FormSubmit (is which I want to call).
Do somebody know why can be the reason of this "error"?
try this
#Html.BeginForm("FormSubmit", "My", FormMethod.Post) {
<input type="submit" value="Submit"/>
}
and remove [HttpPost,ActionName("MyController")] from the action, it is a very strange attribute
This is a fast and reliable way of disabling the button to prevent any "Double click"
<form ... onsubmit="myButton.disabled = true; return true;">
...
<input type="submit" name="myButton" value="Submit">
</form>
You can see the source here
Another way of doing this when submitting is to do an overlay and then redirect
function(Optional, I use it to stop the overlay and just to basically inform the user that the function is done)
HTML:
<input type="submit" onclick="return FunctionOverlay(this);" />
<script>
function FunctionOverlay(btnElement)
{
showOverlay(btnElement);
$('#myForm').submit();
}
</script>
JS:
function showOverlay(buttonElement) {
$(buttonElement.parentNode).css('position', 'relative');
$bgColor = $(buttonElement).attr('data-overlay-color');
if ($bgColor === undefined) {
$bgColor = '#fff';
}
$(buttonElement.parentNode).append('<div class="button-overlay" style="background-color:' + $bgColor + ';"><img src="images/blahblah.gif" /></div>'); //.css('background-color', $bgColor)
}
You can use this to create your own overlay GIF
and then in your controller where you are calling the Method you can end it with
return View("ButtonClicked");
and in your home page create a cshtml ButtonClicked.cshtml
and just create a landing page where you can insert some text for example:
<div class="row">
<div class="col">
<p> Thank you for clicking😊</p>
</div>
</div>
Another option is doing an overlay with a timeout
$('form').submit(function () {
var button = $('#button');
var oldValue = button.value;
var isDisabled = true;
button.attr('disabled', isDisabled);
setTimeout(function () {
button.value = oldValue;
button.attr('disabled', !isDisabled);
}, 3000)
});
Firstable, thank for answer! And I just find the solution.
The problem of the code was if I use disabled it change the request metadata during the form submit event, so I can not make the button disabled.
I fount this solution, it just take off the pointer events from the button and then it prevent the double submit problem.
$('input[type="submit"]').css("pointer-events","none")
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" })'"
i'm trying to upload image using .net core with mvc ajax
here is my code
<form asp-action="AddImages" asp-controller="UserAdmin"
data-ajax-begin="onBeginSubmit" data-ajax-complete="onComplete"
data-ajax-failure="onFailed" data-ajax-success="onSuccessSubmit"
data-ajax="true" data-ajax-method="POST" enctype="multipart/form-data">
<input id="file-input-1" name="Image" type="file" class="uploadimg" data-id="1" accept=".jpg, .jpeg, .png" />
<div class="col-xs-12">
<button type="submit">Save</button>
</div>
</form>
Here is my Model
public class ImageModel
{
[Required(ErrorMessage = "Please Select Image of Product")]
public List<IFormFile> Image { get; set; }
}
And my method
[HttpPost]
public bool AddImages(ImageModel Image)
{
if (!ModelState.IsValid)
{
return false;
}
return true;
}
but Image is null and model always return false
I've just come up against this problem myself, and it seems the only way around it is to use "traditional" ajax to post the form back to the controller. My method was as follows:-
Replace the Submit button with a normal button that calls the Ajax:
<input type="button" class="btn btn-default" value="Save" onclick="javascript:submitForm()" />
Then use Ajax to gather the form data and post it back to the controller action:
function submitForm() {
var formdata = new FormData($('#yourFormId').get(0));
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
//rendering success
},
error: function (xhr, ajaxOptions, thrownError) {
//rendering errors
}
});
}
Hope this helps somebody out. Shame the new "data-ajax" form tags don't seem to be able to handle posting files back.
I am attempting to call a function through a view using jquery.. originally i was using razor's #html.BeignForm but for the web it needs to be converted to jquery
i don't know if i'm on the right path, however this is what i have in razor that's currently working.
#foreach(var up in Model)
{
#up._id
using (#Html.BeginForm("DQPost", "Disqus", new { ID = up._id }, FormMethod.Post))
{
<h7>The thread ID</h7>
<input type="text" name="ThreadID" /><br />
<h7>The message </h7>
<input type="text" name="Message" /><br />
<input type="submit" value="Post Comment"/>
}
}
what i'm trying to do is change the submit to button that then fires off the jquery. and this is the jquery i currently have written out.
<script type="text/javascript">
$(document).ready(function () {
$('#post').click(function () {
var dataToSend = { ID: ID, MethodName: 'DQPost', Message: message };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
}
});
});
</script>
any help would be greatly appreciated.
You are wrong here,$('#post').
$('#post').click(function () {
Post is not an identifier., so, you could declare your own. You could try something like
<input type="submit" id="submitButton" value="Post Comment"/>
Then,
$('#submitButton').click(function () {
will work fine.
Looks like you want to intercept the form submission so you can handle submit yourself with AJAX. If I'm reading that right, instead of attaching to the button's event, attach to the form's event:
$("#my-form-id").submit(function() {
// do my AJAX stuff
return false; // this will prevent the form from being submitted like normal
});