Is it possible to post json to mvc controller without jQuery? - asp.net-mvc

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.

Related

The required anti-forgery form field __RequestVerificationToken is not present

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

Use a Function That Returns Ajax to Ajax.BeginForm's onBegin

EDIT: To be more clear, I am looking to have onBegin call a function that returns a true or false value from an Ajax call. That false value needs to be able to trigger onBegin to abort the form submission, just as if I had returned a false value from a non ajax function.
I need to return a value of false to Ajax.BeginForm's onBegin, if certain conditions exist. This way I can prevent the form from submitting if certain database conditions exist.
However, in order to use the results of an Ajax Get, I would need to craft the function to use callbacks, which means that I cannot have the function used by onBegin return the ajax value. So how can I pass the result into onBegin?
Basically I have:
`Ajax.BeginForm(onBegin="checkIfMyConditionExists();"`}...
function checkIfMyConditionExists(){
$.get(checkConditionURL, function(data){
doSomething(data);
});
How can I get that data (which would be my true or false value) into onBegin?
What you are trying to accomplish without it being synchronous just is not going to happen. You WILL have to perform a synchronous check. Otherwise the check will be called but the form and other things will be submitted before the ajax call has time to say "Wait for me."
In your ajax call to the server you have to set async: false on a $.ajax call. This will make it to where it will expect some sort of result before running the next bit of code. Keep in mind that you wouldn't want to do $.get because there is no option to turn it off.
If you "don't want the UI to hang".... Put some sort of loading icon or text. It's a good practice for "ajax" stuff anyways...
Here is the code you could use :)
function checkIfMyConditionExists () {
$.ajax({
url: checkConditionURL,
async: false,
success: function (data) {
if (!data.success) {
return false;
}
// put your code to run something here!
}
});
}
It really doesn't need to be more complicated than that. Also something to keep in mind when implementing this...
Per the jQuery.ajax documentation:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
Another way to accomplish this would be to do the following.
Use a standard button on the form. (not a submit)
<button id="TriggerButton">Submit</button>
Handle the click of that button. Do your check. Submit the form if it's success!
$(function () {
$("#TriggerButton").click(function (e) {
e.preventDefault();
$.ajax({
url: checkConditionURL,
success: function (data) {
if (!data.success) {
// ruh roh!
return false;
}
// submit le form!
$("#MyForm").trigger("submit");
}
});
});
});
With this method, you could remove the onBegin and it should do what you need it to do. :)
I modified your code with a solution that works:
Ajax.BeginForm(onBegin="return checkIfMyConditionExists();"}...
function checkIfMyConditionExists(){
$.ajax({
url: checkConditionURL,
data: data,
async: false,
success: function (data) {
return data.condition;
}
});
note the async: false option that allows you to wait until the call ends and get the results after that.
My Working code
JavaScript/JQuery
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function StartValidation() {
var result = AjaxCall();
return result;
}
function AjaxCall() {
var Istrue = false;
$.ajax({
url : "#Url.Action("Json", "FileUpload")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({FirstName:'test', LastName:'test1'})
}).done(function() {
Istrue = true;
alert('ok')
})
.fail(function() {
Istrue = false;
alert('not ok');
});
return Istrue;
}
</script>
HTML
#using (Ajax.BeginForm("UploadRequestFile", "FileUpload", new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "return StartValidation();"
}, new { id = "frmUp" }))
{
<input type="submit" name="Submit" value="Submit" />
}
Runtime MarkUp
<form method="post" id="frmUp" data-ajax-method="POST"
data-ajax-begin="return StartValidation();" data-ajax="true"
action="/fileupload/UploadRequestFile?Length=10">
<input type="submit" value="Submit" name="Submit">
</form>
Check the data-ajax-method, data-ajax-begin and data-ajax attributes. Ajax.BeginForm helper emits those attributes. Those attributes mean absolutely nothing to the browser. It's the jquery.unobtrsuive-ajax.js script that understands and interprets them. Without it. So, no need to perform the Submit explicitly.
Action Methods
[HttpPost]
public JsonResult Json(string FirstName, String LastName)
{
//Do the Validation Part here.
return Json(new { Success = true });
}
[HttpPost]
public ActionResult UploadRequestFile()
{
return View();
}

jquery Select2 Ajax - How set value (initSelection)

How set in the drop-down list item selected by the user?
Scenario:
1. User not enter all required values in form
2. Click sent.
3. Page is refresh and value in dropdown list is not selected. How select the value?
I have working script which retrieve data for the list.
$('#userid').select2({
placeholder : " --- select ---",
minimumInputLength: 2,
ajax: {
url: "index.php?modul=getusers",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return { results: data };
}
},
allowClear: true,
formatSelection: function(data) {
return data.text;
}
});
Standard data in ajax call:
{"text":"sample text", "id":"1"}
Input:
<input type="text" value="<? echo $_POST['userid']; ?>" class="input" id="userid" name="userid">
I tried to add the following code, but it doesn't work
initSelection: function(element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("index.php?modul=getusersfriend&q="+id, {
dataType: "json"
}).done(function(data) { callback(data); });
}
},
Make sure that you have a properly formatted JSON Object being returned in your call back in initSelection. The discussion for that has been addressed here already.
But so far looks good. You may want to bind the change event of the select or the submit event of the form to serialize its value before the form is submitted.
You can store its value on your server (yucky) or just serialize the form object and get the value to pass to initSelection when the select2 is loaded.
Which is what would happen here:
var id=$(element).val();
Here is a simple example of serializing your form.
PS: Don't really see what bootstrap has to do with anything.

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

Resources