The required anti-forgery form field __RequestVerificationToken is not present - asp.net-mvc

Could you please help me to solve this issue? I'm implementing sign in form without form or html.beginform because I'm calling the controller /API through Ajax call and based on the status message / success, I want to redirect to some page as per the requirement. Please note, I shouldn't skip the anti-forgery method which has been implemented for the controller method. Thanks.
But I'm not able to proceed further because of "The required anti-forgery form field __RequestVerificationToken is not present"
My View is as follows :
""<input data-bind="value: UserName" type="text" name="username" />
<button type="button" data-bind="click:LoginMethod"> Login </button>""
And the Ajax code is as follows
self.LoginMethod = function () {
//Ajax call to Insert the Customer record
$.ajax({
type: "POST",
url: "http://localhost:8089/Home/SignIn/",
data: ko.toJSON(CustData), //Convert the Observable Data into JSON
success: function (data) {
console.log("success");
alert("Record Added Successfully");
},
error: function () {
console.log("failed");
alert("Failed");
}
});
Appreciated your's help.

Change data: ko.toJSON(CustData) to data: ko.toJS(CustData).
And you should be good to go

Related

Is it possible to post json to mvc controller without jQuery?

I would like to post several input values to controller as a json string with only one method argument for example:
<input name="x" value="">
<input name="y" value="">
public void GetAsJson(string json)
{
}
And doing so without jQuery and with default model binding?
It is impossible to perform what you are saying without any kind of Javascript at all. With JSON, the JS stands for Javascript and Javascript is needed to perform an Ajax call anyways.
Here is how I would do it.
Remember that on the C# side of things that you aren't really accepting a JSON object, you are actually just accepting a list.
Here is the post that you are wanting. It is almost a string like you suggested however, the difference is because in your AJAX call, you need to specify the JSON.stringify and the dataType: json.
public ActionResult FruitPost(List<String> Fruit)
{
return null;
}
Here is the view:
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var fruit = ["apple", "orange", "bananna"];
jQuery.ajax({
type: "POST",
url: "#Url.Action("FruitPost")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(fruit),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
If you are DEAD SET on doing an ajax call without JQuery... I would suggest reading this: https://www.sitepoint.com/guide-vanilla-ajax-without-jquery/
After doing so, you might change your mind.

How to keep reCaptcha on screen after failed input

I have an asp.net MVC site with a bootstrap modal that has a reCaptcha form on it. It correctly validates the input upon submit, but if it's not valid, upon rendering the view so they can try again, the captcha disappears and the javascript console shows this error: "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened." I have to refresh the page and reopen the modal to see the Captcha again.
Snippet of code containing the Captcha (public/private keys are in web.config):
<input type="hidden" name="ProductID" value="#Model.ProductID" />
<input type="hidden" name="UserTypeID" value="#Model.User.UserTypeID" />
#Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean)
<div id="request-error-summary">
#Html.ValidationSummary(false, "All fields are required.")
</div>
Controller code upon submitting form:
public PartialViewResult SubmitRequest(RequestKitModel kitModel)
{
/* code removed for brevity */
RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
ModelState.AddModelError("", "Captcha answer cannot be empty.");
return PartialView("_Request", kitModel);
}
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
ModelState.AddModelError("", "Incorrect captcha answer.");
return PartialView("_Request", kitModel);
}
/* code to ruun upon success of captcha input */
//close modal and return to results
return PartialView("_Confirmation");
}
Jquery Ajax call to SubmitRequest... I think the way I'm loading the partial view may be the culprit.
if ($('#request-form').valid()) {
$.ajax({
url: "/SubmitRequest",
type: "POST",
data: $("#request-form").serialize(),
success: function (data) {
//show the confirmation (thanks) modal
$("#request-modal .modal-content").html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
window.location.href = '#Url.Action("Error")';
}
});
}
UPDATE: I changed it to use recaptcha_ajax.js since I am loading it after an ajax request. Now I get this error: "cannot set property 'innerhtml' of null" from the recaptcha_ajax.js file (cannot tell which object it's throwing this error on). Instead of calling Html.Recaptcha in the razor file, I now have this:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha1"></div>
And the updated AJAX call:
$.ajax({
url: "/SubmitRequest",
type: "POST",
data: $("#request-form").serialize(),
success: function (data) {
//show the confirmation (thanks) modal
$("#request-modal .modal-content").html(data);
Recaptcha.create("6LedL_sSAAAAAJuozIfRiVfNOCHs-jlTn6NM4c-T",
"recaptcha1",
{
theme: "white",
callback: Recaptcha.focus_response_field
}
);
console.log("done loading html");
console.log('captcha control: ' + $("#recaptcha1").length);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
window.location.href = '#Url.Action("Error")';
}
});
Try and put the javascript reference
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
in your main layout, I got the same error you did because the javascript library wasn't fully loaded.
You should also check that the div exists in the callback.
I hope this helps,
Salvador

knockout.js redirect in view model

I have the following code on cshtml page.
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" onclick="location.href='#Url.Action("ExportInventory", "Inventory")'">EXPORT INVENTORY</button>
</div>
How do I make this work in my view model?
I think I almost got it, but need some help
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" data-bind="click: exportInventory">EXPORT INVENTORY</button>
</div>
My viewmodel has this code:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: '/Inventory/ExportInventory', type: 'POST' }).done(function (data) {
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
I tried this, but I get errors:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: 'location.href="#Url.Action("ExportInventory", "Inventory")"', type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
Can someone help me figure this out?
The way you're trying to pass in the url to the ajax call is probably not working the way you expect. Also, you wouldn't need the location.href= to be part of the url parameter in the $.ajax() call.
If your view model is coded in a script tag right in your cshtml page, you can try this:
<!-- cshtml razor view code for generating the html is above this line -->
<script>
var viewModel = {
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
//allow razor to build a javascript string for you when it renders the html
//when the browser parses this script, it will just see a simple string
var myURL = '#Url.Action("ExportINventory", "Inventory")';
//pass your variable to the jQuery ajax call
$.ajax({ url: myURL, type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
//this line of code would never be called because the browser has navigated away from this page...
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
};
</script>
Load the page and view source. If the var myUrl = line is the correct URL to your controller as a string, then you know that razor kicked in and prepared that for you on render.

Load partial view into div on button click without refreshing page

I know this question might be repeated but my query is different let me explain, I have a drop down in page and by selecting value in drop down list,and I click on submit button.. I want by click on submit button I need to load partial view in tag that is list of records of selected drop down list value.
i tried this :
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Content("~/Search/MDLNoDataList")',
data: mdlno,
success: function (data) { $("#viewlist").innerHtml = data; }
});
});
but not getting result And I m using these many jquery plugins
<script src="../../Scripts/jquery-migrate-1.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
If i understand correctly, below is what you need to do.
HTML Example:
<div id="records">
</div>
<select id="ddlRecordType">
<option value="1">Type 1</option>
<option value="2">Type 2</option>
</select>
<input type="submit" value="Load Records" id="btn-submit" />
jQuery Code
$(document).ready(function(){
$('#btn-submit').click(function(){
var selectedRecVal=$('#ddlRecordType').val();
$('#records').load('/LoadRecords?Id='+selectedRecVal);
return false; // to prevent default form submit
});
});
Here ?Id= is the query string parameter passed to server to get
the selected item in dropdown.
Edit: The below answer was added, as the question content changed from initial post
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("MDLNoDataList","Search")',
data: mdlno,
success: function (data) {
// $("#viewlist")[0].innerHtml = data;
//or
$("#viewlist").html(data);
}
});
return false; //prevent default action(submit) for a button
});
Make sure you cancel the default action of form submission by returning false from your click handler:
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("MDLNoDataList", "Search")',
data: mdlno,
success: function (data) {
$("#viewlist").html(data);
}
});
return false; // <!-- This is the important part
});
And if you are using the WebForms view engine and not Razor make sure you use the correct syntax to specify the url:
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '<%= Url.Action("MDLNoDataList", "Search") %>',
data: mdlno,
success: function (data) {
$("#viewlist").html(data);
}
});
return false; // <!-- This is the important part
});
If you do not return false, the form is simply submitted to the server when you click on the submit button, the browser redirects away from the page and obviously your AJAX call never has time to execute.
You will also notice some improvements I made to your original code:
Using the Url.Action helper when pointing to a server side controller action in order to take into account routes defined in your application.
Using jQuery's .html() method instead of innerHTML to set the contents of a given element.
You need AJAX for this purpose.
$.get(url, data, function(data) { $(element).append(data) });
and Partial View that is vague.
element {
overflow:hidden;
}

jQuery Ajax Form Submit Fails

I am developing an MVC4 mobile app that uses several forms which are loaded into a section on the layout via ajax. I've got jQuery mobile set with Ajax turned off so I can manage the Ajax myself. Most of the forms work fine, the load and submit via ajax as they should. However, so far there is one form that refuses to fire the form submit and submit the form via ajax like the rest. First, the form is loaded when a user clicks to add a contact and this works fine:
// Handle the add contact button click
$('#btnAddNewContact').on('click', function (e) {
e.preventDefault();
// Make sure a location was selected first.
var locationID = $('#cboLocation').val();
if (locationID.length === 0) {
//$('#alertTitle').text('REQUIRED');
$('#alertMsg').html("<p>A Contact must be associated with a Location.</p><p>Please select or add a Location first.</p>");
$('#alertDialogDisplay').click();
} else {
SaveOpportunityFormState();
$.cookie('cmdLocationId', locationID, { path: '/' });
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'GET',
cache: false,
success: function (response, status, XMLHttpRequest) {
$('section.ui-content-Override').html(response);
// Refresh the page to apply jQuery Mobile styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
},
complete: function () {
$.cookie('cmdPreviousPage', '/Opportunity/Add', { path: '/' });
AddContactLoad();
ShowSearchHeader(false);
$.mobile.loading('hide');
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
Notice that after successfully loading the form the AddContactLoad() function is fired. This works fine and here is that code:
function AddContactLoad() {
$('#contactVM_Phone').mask('(999) 999-9999? x99999');
$('#frmAddContact').on('submit', function (e) {
e.preventDefault();
if ($(this).valid()) {
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'POST',
cache: false,
data: $(this).serialize(),
success: function (response, status, XMLHttpRequest) {
if (!response) { // Success
ReturnToAddOpportunity();
} else { // Invalid Form
$('section.ui-content-Override').html(response);
// Force jQuery Mobile to apply styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
AddContactLoad();
$.mobile.loading('hide');
}
},
complete: function () {
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
$('#btnCancel').on('click', function (e) {
e.preventDefault();
// See where add contact was called from.
var previousPage = $.cookie('cmdPreviousPage');
if (previousPage.indexOf("Detail") >= 0) {
ReturnToOpportunityDetails();
} else {
ReturnToAddOpportunity();
}
return false;
});
}
If I click the cancel button, that code is fired so I know this is working too. Here is my form code:
#using (Html.BeginForm("Add", "Contact", FormMethod.Post, new { #id = "frmAddContact" }))
{
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
-- Form Fields Here --
<div class="savecancel" >
<input type="submit" value="Save" data-mini="true", data-theme="b", data-inline="true" />
Cancel
</div>
}
As you can see the form is named frmAddContact and that is what the AddContactLoad() function is attaching the submit event to. To save my sole I cannot figure out why the form does not submit via the ajax post like every other form in the app. Am I missing some kind of initialization, I just don't know. If anyone can please help I'd really appreciate it!!
As it turns out, I had created a custom unobtrusive Ajax validator for a phone number then copied and pasted it to do the same with a zip code. Unfortunately in the process I forgot to rename a variable and thus an error was occurring in the validation script which caused the problem. In the mean time, if you're reading this, you might take a note of the code here and how to inject HTML into a page via Ajax and jQuery mobile. I've never found this in a book or on the web and it contains some very useful methodology and syntax. On the form submit the reason I'm checking for the empty response is I just return null from the controller to validate the form was valid and the save worked in which case I send them to a different HTML injection i.e. that page they originally came from. If null is not returned I inject that page with the HTML containing the original form and error markup so the user can make corrections then resubmit. I'm also calling a form load method that attaches handlers to the HTML once it's injected into the main page. Hope this helps somebody!

Resources