Submit a form as JSON (no AJAX) - asp.net-mvc

Is it possible to submit form data as JSON, without using AJAX?
I've tried changing the enctype:
<form enctype="application/json"></form>
But that's not a valid value according on w3schools
The reason I would like this behaviour is that the requested URL will return a file, which I obviously can't do anything with if I use AJAX. I would like to send JSON data marked as Content-Type: application/json so that ASP.NET MVC will use its JSON binding.

Yes, you can serialize form like an object with plugin. I write a sample for you;
//Head
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.serialize-object.js"></script>
You can download plugin from here
//Form
<form id="frm">
<input type="text" name="Model[Firstname]">
<input type="text" name="Model[Lastname]">
<input type="text" name="ModelDetail[PhoneNumber]">
...
<button type="button" onclick="sendForm()">Send</button>
</form>
//JS
function sendForm(){
model_data = $("#frm").serializeObject();
$.ajax({
url: 'YOUR_SERVICE_URL',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(model_data),
dataType: 'json',
success:function(e){
// I know, you do not want Ajax, if you callback to page, you can refresh page here
}
});
Good luck!

Could you use JSON.stringify() to serialize your client side object and then stuff that into a hidden input and submit your form...and then in the controller side pull it back out of the Request.Form and deserialize it into your object?
[Edit]
Just saw in the comment section underneath of the original question that this was essentially a duplicate post and that this stackoverflow worked as a solution.

you can try;
// html
<form type="POST" action="/Home/Test">
<input id="foo" value="hede">
</form>
// dto
public class TestInDto{
public string foo {get;set;}
}
// home controller
[HttpPost]
void Test(TestInDto inDto){
var foo = inDto.foo;
}

As per W3C standards you can't pass the data like JSON using
<form enctype="application/json"></form>
Description
User agents that implement this specification will transmit JSON data from their forms whenever the form's enctype attribute is set to application/json. During the transition period, user agents that do not support this encoding will fall back to using application/x-www-form-urlencoded. This can be detected on the server side, and the conversion algorithm described in this specification can be used to convert such data to JSON.
The path format used in input names is straightforward. To begin with, when no structuring information is present, the information will simply be captured as keys in a JSON object
Reference DOC

You can now set form enctype='application/json' according to the new W3C standards published on 29 May 2014.
You can check it : http://www.w3.org/TR/html-json-forms/

You can use Form2js.It is designed by google and it is easy to use library.
https://github.com/maxatwork/form2js
Also , It can be modified according to user requirement .You can check their license .You can Find the basic examples of this javascript file using the link below:
http://form2js.googlecode.com/hg/example/test.html

Try this simple store your POST array in variable and then encode it as json obj.
like this-->
$postarray=($_POST);
$jsondata=json_encode($postarray);
Sorry its for PHP

Related

Posting SVG string to Controller works locally but not on server

I have a form that I'm posting that contains 2 numeric values and a long string containing an SVG (generated using Fabricjs). The controller uploads the SVG and outputs a PDF containing it. The reason I'm using a standard form post instead of Ajax POST is because I understand that ajax cannot return a file download.
I have maxJsonLength, aspnet:MaxJsonDeserializerMembers, and maxRequestLength all set to values much higher than what's involved here (10k of text), and I don't think the json-related ones come into play here anyway since it's a standard form post.
This works perfectly when I run it locally in Visual Studio. Once it's published to the server, it fails. I attached to the process with remote debug, and it's not even hitting the controller. I have a similar controller action that also accepts the same SVG string, and that's not working either.
In the network console, the action returns a 200. When I look at the headers, I can't see any difference between what's posting to the server vs. what I see locally. Elmah is not capturing any error, so I can't even figure out where to go at this point to find out what's wrong.
Here's the form. I added the enctype at the suggestion of another SO post, but that doesn't make a difference.
<form action="/Product/ExportSVG" enctype="application/x-www-form-urlencoded; charset=UTF-8" id="svgForm" method="post">
<input type="hidden" id="svgProjNo" name="svgProjNo" value="1111">
<input type="hidden" id="svgLineID" name="svgLineID" value="">
<input type="hidden" id="svgData" name="svgData" value="">
</form>
The script that posts the form:
var svgtext = canvas.toSVG(null, reviver);
$("#svgLineID").val($("#LineItem_ParentID").val());
$("#svgData").val(svgtext);
$('#svgForm').trigger('submit');
The controller:
[HttpPost]
public ActionResult ExportSVG(decimal svgProjNo, decimal svgLineID, string svgData)
{
...
}
You may need to encode SVG data in base 64 format.

Get QueryStrings in browser url in jquery get request

I would like to send a get request with jquery but the get function does not put the query strings in the address bar.I tried setting async to false but it still does not work.
$("#searchForm").submit(function (event) {
var x = $("#category").serialize();
$.get("Home/test", x, function (data) {
alert(data);
});
event.preventDefault();
});
The code above does not put the query strings in the address bar like a normal get request would.
hence i should have in the browser address bar something like Home/Text/?category=laptop
for example
any other solutions to specify what querystrings i can put in the address bar are welcome.
form id="searchForm" action="#Url.Action("Index")" method="get">
<input type="text" name="search" id="search />
<div id="price">
<input type="text" id="PriceMin" name="PriceMin" />
<input type="text" id="PriceMax" name="PriceMax" />
</div>
<input type="submit" value="submit"/>
</form>
as an example i dont want in the url querystrings of
?search=volvo&PriceMin=&PriceMax=
In other words, the input fields that are null should not be placed in url on a get request.
thx.
Found something and its working why i didnt think of this before is beyond me
$("#searchForm").submit(function (event) {
if ($("#PriceMin").val() == "") { $("#PriceMin").prop("disabled", true); alert("isnull");}
});
i disable the input field if it is "" just before the form is sent.Thus the query string of "priceMin" is not sent because the element is disabled.
The reason why the address bar doesn't change is because when you make an AJAX request with javascript, this request is made in the background. The whole point of AJAX is to make requests without navigating away form the current page. If you change the url in the address bar that would trigger the entire page to be reloaded. So what you are trying to achieve is impossible. You could use the fragment portion of the url (the part that follows the #). You could modify this part of the url without causing the browser to navigate away. Take a look at the following article: http://ajax.rswebanalytics.com/seo-for-ajax/#!ajax-crawlable-urls
Thus you could have the following url:
http://example.com/Home/Text/#category=laptop
In order to manipulate the fragment portion of the url in javascript you could use the window.location.hash property. Bear in mind though that this part of the url is never sent to the server. It is only intended to be used on the client.
As far as your second question about the empty strings is concerned, there's no way to achieve that in pure HTML. You will have to write javascript. Basically here you will have to subscribe to the .submit event of the form and manually build the target url that you will redirect to and exclude parameters that have empty values. Then manually redirect to this url using the window.location.href property. Also don't forget to cancel the default action of the submit by returning false.

Refactoring HTML Markup from POST to GET

I have the following mark up in an ASP.NET MVC view (this is a Twitter Bootstrap search box):
<form action="#Url.Action("Results", "Search")" method="post">
<input type="text" class="search-query" id="SearchTerm" name="SearchTerm" />
</form>
This code works as expected, but using a post here is causing problems.
How can I change this markup to pass the search query as a URL argument instead? I'm not really sure how to even approach this short of keeping the existing markup and then redirecting from the controller. I'm thinking there must be a more efficient way than that.
You should be able to change method="post" to method="get" and get the desired result. The form, with a get method setting, pushes the fields in the form to the querystring by its default behavior.
As a workaround, if the default behavior doesn't suit you, you could catch the submit event of the form, and do:
window.location = form.action + "?SearchTerm=" + document.getElementById("SearchTerm").value
Something like that, where form is a reference to the form element. You can build the link and redirect using javascript, which is a get request.

Looking for an AJAX jQuery way to get four field values and send them to server

I have an MVC application. I would like to get the values of a variable number of field values such as:
field_1, field_2 .. field_4
send them to my controller and then change the value of a Div's text based on the response. I never really used jQuery for anything like this. Do I need to use JSON to pack up the values and if so how do I unpack them on server. Is it something I can do easily? I hope for some advice.
I think,
you can find an answer at here. You should use the 'post' method for sending and receiving the data.
If you want to read more about JSON objects in different language read http://www.json.org
Assuming the inputs are in a from tag you can get the id of the form, serialize it, create an ajax request to the server, process it, then return data. It's look something like this.
function sendToServer() {
var sendData = $('#myForm').serialize;
$.get('/url/to/server/', sendData, function(returnData){
//This is called on success
$('#myDiv').html = returnData;
});
}
Now this assumes also that the div has an id 'myDiv' and that returnData is already html formatted. It doesn't have to be you can do more processing inside the success call back
How to make the Ajax Call
Jquery .get
How to serialize a form
Jquery serialize
Brombombs answer is mostly complete. The '.serialize()' essentially takes the name of the html elements and the value and puts it into a JSON array structure. When you do a .get or a .post and have that data as the data to send, they will be available to PHP in global variables. .get the variables will be found in the $_GET variable and if doing a post, a $_POST variable.
for example
<form id="myForm">
<input name="firstName">John</input>
</form>
$('#myForm').serialize() returns a json
{ 'firstName' : 'John' }
and doing a .post... php can access this as
echo $_POST['firstName'];
//prints John

Insert cakephp POST params into URL

I have this form below which contains two checkboxes to sort some products:
<form id="FiltreExtraForm" action="" method="post" name="FiltreExtraForm">
<input id="ProductsDeliveryPrice" type="checkbox" value="1" name="data[Products][delivery_price]"/>
<input id="ProductsPicture" type="checkbox" value="1" name="data[Products][picture]"/>
</form>
After POST I do the filtering but I also want to add received parameters to URL E.g: /products/index/delivery_price:1/picture:0 . Is this possible. How can I do that?
Note: I don't want to use GET to send form info.
Sounds like you are looking to do a Post/Redirect/Get.
Here are two examples of doing this in CakePHP:
Searching on surname
Searching on multiple fields
The two main advantages of redirecting a POST to a GET request are:
Users don't get the "Do you want to resubmit?" dialog if they refresh
The resulting page/query can be bookmarked
In the action to which you post, you could simply prepare the GET url and then redirect to this url. The action for that url then does the filtering.
If I understand you correctly (and I'm not sure that I do), you can pass additional variables on the query string of the form's action quite easily. Conventionally, that might look like this:
<form id="FiltreExtraForm" action="/products/index?delivery_price=1&picture=0" method="post" name="FiltreExtraForm">
Using Cake, you should be able to do the same without the traditional query string if you'd rather (though the traditional method above will also work):
<form id="FiltreExtraForm" action="/products/index/delivery_price:1/picture:0" method="post" name="FiltreExtraForm">
I would recommend looking at the form helper or at least constructing the action URI using helpers, but this should get you what you're after.

Resources