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!");
}
});
}
Related
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)
{
....
}
I have an issue where the hidden values in a form are not updating when the new ActionResult is returned.
For example, a user will check several records and click the Update Completion button. This makes an Ajax called to the UpdateCompleted action that sets a date for the checked records and once the Ajax call returns the form is submitted. After performing some logic in the form submit Action method, an updated model is returned with the IsChecked value set to false for all records in the model, but the form is retaining the previous checked value due to the generated id below having the same value.
Code
<td>
#Html.CheckBoxFor(model => Model.WorkOrderDetails[x].IsChecked)
#Html.HiddenFor(modelItem => Model.WorkOrderDetails[x].IsChecked)
#Html.HiddenFor(modelItem => Model.WorkOrderDetails[x].WorkOrderEntityId)
#Html.HiddenFor(model => model.WorkOrderDetails[x].WorkOrderId)
</td>
Rendered HTML
<td>
<input data-val="true" data-val-required="The IsChecked field is required." id="WorkOrderDetails_0__IsChecked" name="WorkOrderDetails[0].IsChecked" type="checkbox" value="true"><input name="WorkOrderDetails[0].IsChecked" type="hidden" value="false">
<input id="WorkOrderDetails_0__IsChecked" name="WorkOrderDetails[0].IsChecked" type="hidden" value="False">
<input id="WorkOrderDetails_0__WorkOrderEntityId" name="WorkOrderDetails[0].WorkOrderEntityId" type="hidden" value="ODU=">
<input id="WorkOrderDetails_0__WorkOrderId" name="WorkOrderDetails[0].WorkOrderId" type="hidden" value="NjQ4OTU3">
</td>
Submit Code
#using(#Html.BeginForm("Index", "WorkOrderMaster", FormMethod.Post, new { id = "workOrderMasterForm" }))
{
<div>
<div class="project-buttons">
<div class="btn-group">
<input id="submitCompletion" class="btn btn-success" value="Update Completion" data-submit-url='#Url.Action("UpdateCompleted", "WorkOrderMaster")' />
</div>
</div>
$(function () {
$('#submitCompletion').click(function () {
$.ajax({
type: 'POST',
url: $(this).data('submit-url'),
data: $('#workOrderMasterForm').serialize(),
success: function (data) {
$('#workOrderMasterForm').submit();
}
});
});
});
I would expect the new values from the model to be used but this is not occurring.
Is it recommended to code the input values manually in this situation in order to avoid the following format?
ClassName_Index_PropertyName
Thanks in advance for the time you took to look at this question.
Based on the provided code, you are performing an AJAX call to the server but expects the values to be cleaned up after the operation is finished.
It will not work since you are not refreshing the page. To clean up the form values without refreshing the page you need to do a small change in your code:
$(function () {
$('#submitCompletion').click(function () {
$.ajax({
type: 'POST',
url: $(this).data('submit-url'),
data: $('#workOrderMasterForm').serialize(),
success: function (data) {
$('#workOrderMasterForm').reset();
}
});
});
});
The change is in the success promise where "$('#workOrderMasterForm').sugmit();" changed to "$('#workOrderMasterForm').reset();".
In an effort to keep moving on this. I moved the form to a partial view, and added a div to load the partial view into. Anytime an event fires on the page thru many filters or the users submitting checked records the div is cleared and reloaded. This solved my issue.
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'm having an issue with a dropdown list using Knockout. I'm fairly new to this. The scenario is that when I edit some data, I call a Web Api to return some information in JSON. The JSON is then mapped and displayed for an end user to edit if they wish to. I have two dropdown lists (manufacturers and ranges). The manufacturer dropdown list gets populated and set to the correct value which is returned. The issue is that the second dropdown list gets populated but does not get set to the correct value. Instead it remains at the default "select" value. Would someone be able to explain why this happens or point me in the right direction?
My code is as follows. I have trimmed it down but can provide any further code if need be. Many thanks.
JS
/// <reference path="../knockout/knockout-3.4.0.debug.js" />
/// <reference path="../jquery/jquery.min.js" />
var deal = function () {
var self = this;
// These are the initial options
self.ManufacturerOptions = ko.observableArray();
self.VehicleManufacturerId = ko.observable();
self.RangeOptions = ko.observableArray();
self.VehicleRangeId = ko.observable();
var Deals = {
ManufacturerOptions: self.ManufacturerOptions,
VehicleManufacturerId: self.VehicleManufacturerId,
RangeOptions: self.RangeOptions,
VehicleRangeId: self.VehicleRangeId,
};
self.Deal = ko.observable();
self.Deals = ko.observableArray();
RetrieveDeals();
GetManufacturers();
self.EditData = function (Deal) {
GetManufacturers();
GetRanges(Deal.VehicleManufacturerId);
self.Deal(Deal);
};
function GetManufacturers() {
$.ajax({
url: 'http://localhost:47633/api/Vehicle/GetManufacturers',
type: 'get',
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (dataReturned) {
self.ManufacturerOptions(dataReturned);
}
});
}
function GetRanges(manufacturerId) {
$.ajax({
url: 'http://localhost:47633/api/Vehicle/GetRanges?manufacturerCode=' + manufacturerId,
type: 'get',
crossDomain: true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (dataReturned) {
self.RangeOptions(dataReturned);
}
});
}
};
$(document).ready(function () {
ko.applyBindings(new deal());
});
ASCX Control
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Home.ascx.cs" Inherits="Desktop.Controls.DealBook.Home" %>
<h1>DealBook</h1>
<div data-bind="if: Deal">
<div>
<h2>Update Deal</h2>
</div>
<div>
<p>Manufacturer: <select id="Manufacturer" data-bind="options: ManufacturerOptions, optionsCaption: 'Select Manufacturer', optionsValue: 'cman_code', optionsText: 'cman_name', value: Deal().VehicleManufacturerId, event: { change: manufacturerChanged}"></select></p>
<p>Range: <select id="Range" data-bind="options: RangeOptions, optionsCaption: 'Select Range', optionsValue: 'cran_code', optionsText: 'cran_name', value: Deal().VehicleRangeId, event: { change: rangeChanged }"></select></p>
</div>
<input type="button" id="btnUpdateData" class="btn btn-primary" value="Update Deal" data-bind="click: UpdateData" />
<input type="button" id="btnCancel" class="btn btn-primary" value="Cancel" data-bind="click: Cancel" />
UPDATE
I believe the issue is that my code is trying to update the dropdown list to the selected value before the options are returned from the Web API. Any thoughts on how I can bind the value to the deal once the options are returned?
Fixed by using Jquery promises to defer method calls until complete.
I now call $.when(GetRanges(Deal.VehicleManufacturerId)).then(function () { self.Deal(Deal) }); instead of
GetRanges(Deal.VehicleManufacturerId);
self.Deal(Deal);
I am having a problem using client side validation in combination with Data Annotations.
The project is using ASP.NET Framework 4.5, a Web Application with the MVP pattern and jQuery Ajax calls to dynamically load user controls.
This is the (stripped) user control which contains the input element that needs to be validated:
<form id="insertArtist" class="form-horizontal">
<fieldset>
<legend>Add new artist</legend>
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<asp:TextBox runat="server" ID="name" ClientIDMode="Static" CssClass="input-medium"></asp:TextBox>
<ml:DataAnnotationValidator runat="server" ID="davName" ControlToValidate="name" EnableClientScript="true" PropertyToValidate="Name" SourceTypeName="Music.Library.Domain.Models.Artist, Music.Library.Domain">
</ml:DataAnnotationValidator>
</div>
<div class="form-actions">
<button id="save" class="btn btn-primary" name="submit" type="submit">Save</button>
<button id="cancel" class="btn">Cancel</button>
</div>
</div>
</form>
This user control get's dynamically loaded using the following ajax call:
$('#add').click(function () {
$.ajax({
url: "/Artist/Manage/Insert.ascx.axd",
type: "POST",
dataType: "html",
success: function (obj) {
$('#body_artist').html($(obj));
}
});
});
This is the jquery executed when a user clicks save:
$('#save').click(function (event) {
event.preventDefault();
$.ajax({
url: "/artist/add.axd",
type: "POST",
dataType: "html",
cache: false,
async: true,
data: 'Ajax=true&' + $('#insertArtist').serialize(),
beforeSend: function (jqXHR, settings) {
$('#loading').show();
},
success: function (data) {
if (data == "succes") {
showNotification('succes', 'Succesfully added artist');
} else {
showNotification('error', 'Error while adding artist: ' + data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
showNotification('error', 'Error while adding artist: ' + data);
},
complete: function () {
$('#loading').hide();
}
});
});
Now, since there is no trigger from an asp.net control the custom data annotation validator will not validate.
I've tried validating using Javascript, using the Page_ClientValidate(), ValidateEnable() and Validate() methods. Unfortunately when trying this I keep getting the same error over and over:
Page_ClientValidate is not defined
Same story for the other methods.
I'm at wits end here.
Is it because the UserControl is dynamically loaded that these client validation methods do not work? I've set EnableClientScript to true.
Or does anyone have another idea on how to implement this? I'd really like to use the Data Annotations.
Thanks in advance!
It can be a solution
http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/
Especially, it is a dublicate of this question Unobtrusive validation not working on dynamically-added partial view which also refers to XHalent blog