MVC and JQuery: Best practice for retrieving form data - c#

I have some JQuery that uses Ajax to send information back to my controller to be processed
I am doing it like this:
//Define my controls
<%=Html.TextBox("PName", Model.PName, new { id = "pName" })%> ...
....
....
//Get the values from my controls
var param1= $("#pName").val();
....
....
//Define the return URL. Is this how to send info back?
var url = '<%= Url.Content("~/Port/SaveRowAjax") %>/?ID=' + id
+ "&param1=" + param1
+ "&param2=" + param2
+ "&param3=" + param3
+ "&param4=" + param4
+ "&param5=" + param5;
$.ajax({
url: url,
success: function(html) {
alert("Success!");
},
});
//My c# code, that processes the request
public void SaveRowAjax(string param1 ....)
{
...
}
Is this the best way of doing it with MVC?
It seems a bit messy when i am contructing the URL to post back to the server

Try using SerializeArray for submitting your form items. It'll box all their values into a JSON object.
var link = "/Port/SaveRowAjax";
var formData = $(":input").serializeArray();
$.post(link,formData);

You can try to use such syntax with jQuery
$.post(link, {param1: param1, param2: param2 });

The way that works for me is this:
jQuery.ajax({
url: '#Url.Action("SaveRowAjax", "Port")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ param1: param1, param2: param2, param3: param3 }),
success: function (result) { }
});

Theres a few ways to do this. I prefer the method outlined here:
http://weblogs.asp.net/mikebosch/archive/2008/02/15/asp-net-mvc-submitting-ajax-form-with-jquery.aspx
Yes, it is based on an older version of MVC but the real beef of the technique is the use of jQuery (which hasnt changed).
One limitation of the technique is that it wont work with file uploads, however, there is a jQuery plugin for doing ajax form posts that does support file uploads (I think through a hidden iframe).
edit:
I think the best reason to use this technique is that if the user has javascript disabled, the form will still work.

Related

Push Table to screen

I have an AJAX request when a branch of my JSSTree is clicked
$("#jstree").bind("select_node.jstree", function(evt, data)
{
var idArgument = data.node.text;
$.ajax(
{
type: "POST",
url: "WebForm1.aspx/brancheSelectionnee",
data: JSON.stringify({ id: idArgument }),
contentType: "application/json; charset=utf-8",
success: function(msg)
{
;
}
});
});
So, I call this function, which make a new "page" (because it's static) and call a function that return a System.Web.UI.WebControls.Table.
public static string brancheSelectionnee(string id)
{
var page = (WebForm1)HttpContext.Current.CurrentHandler;
System.Web.UI.WebControls.Table tableau = page.brancheSelectionneeNonStatique(id);
var stringWriter = new StringWriter();
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
tableau.RenderControl(htmlWriter);
}
string tableauString=stringWriter.ToString();
return "randomstring";
}
Big problem here: My "tableau" is updated, with what I want (I see this with the htmlWriter) but.. I don't know how put it in my screen!
I have it in my C# code, but I want it in the screen, and not just here.
I have "tableauArticle" which is a real System.Web.UI.WebControls.Table, in my ASP.net code.
I tried some things, like putting "tableauArticle" as Static, then
tableauArticles = tableau;
But I didn't see any changement. I think that I updated a table in the page that I don't display
I think that the main problem is that my pagee isn't refresh or I do my tables wrong.
You do an AJAX request, so there is no page refresh. You just get a string (with HTML) back from your server method. You then have to manually put that string on your page. This happens in the success callback function which in your code is empty. As first step try something like this:
success: function(msg)
{
$('<div class="newtable">').html(msg).appendTo('body');
}
On the server-side your method brancheSelectionnee needs the AjaxMethod attribute so that it can be called with AJAX:
[Ajax.AjaxMethod()]
public static string brancheSelectionnee(string id)
(It also should return tableauString; not "randomstring", right?. And I am not sure if you can use the HttpContext.Current.CurrentHandler there, but that is for a second step if the basic AJAX stuff works.)
Here is one tutorial for all this which gives you an overview.
For the answer, it is 100% Raidri solution :
$('#tableauArticles').empty();
$('<div class="newtable">').html(msg.d).appendTo('#tableauArticles');

Esri Query, JQuery Ajax: Not Liking a Ajax Return

I have a JQuery Ajax Call as per the following code:
$.ajax({
type: "POST",
url: "spaceplanning_database.asmx/GetRoomDataAttributes",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
restricted_attributes_global = msg.d;
console.log(msg.d);// "OBJECTID", "Room", "Floor", "OBJECTID_BLDG", "Room_GUID", "PKey", "SHAPE"
var featureLayer = new FeatureLayer("http://gisserver/xxx", {
mode: FeatureLayer.MODE_SNAPSHOT,
//outFields: [restricted_attributes_global], //doesn't work
outFields: ["OBJECTID", "Room", "Floor", "OBJECTID_BLDG", "Room_GUID", "PKey", "SHAPE"],
});
map.addLayer(featureLayer);
}
});
Basically, this calls a C# Web Service and gets some database column names (such as OBJECTID, Room). The column names are padded in the Web Service with double quotes, per
string allowed_loc = "\"" + reader["COLUMN_NAME"] + "\"";
in a loop.
The console.log in the code above shows the output for msg.d; but when this assigned to the restricted_attributes_global variable and used in the Esri query then I see an error:
esri.layers.FeatureLayer: unable to find '"OBJECTID","Room","Floor","OBJECTID_BLDG","Room_GUID","PKey","SHAPE"' field in the layer 'fields'
But, as in the code above, I copy/paste the console.log value as hard-coded then the Esri query works. Maybe I need to put the double quotes in C# in a different way, or type charset to something else in the Ajax call? What could be happening?
I think this question falls somewhere in between JQuery, C# and Esri queries.
As I figured out in my Comment above, I had to make an array object to pass to the outFields variable and I just couldn't make it work with the FeatureLayer mode. So I ended up using a QueryTask. Here is relevant code:
...//code as above this line
restricted_attributes_global = msg.d;
var array = restricted_attributes_global.split(',');//converting to array
var query = new esri.tasks.Query();
var queryTask = new esri.tasks.QueryTask("http://gisserver/xx");
query.where = "OBJECTID_BLDG=12";
query.outSpatialReference = { wkid: 102100 };
query.returnGeometry = true;
query.outFields = [array];// passing the array
QueryTask was the better route for my application anyway. The C# code is changed to remove the double quotes now:
allowed_attributes.Add(reader["COLUMN_NAME"].ToString());
Everything working like a charm now.
HTH.

JQuery values passed to WebApi is always null

I am having trouble with Web Api and was hoping someone here might be able to help me.
I have a jQuery method as follows ...
function OnInsert(evt) {
var truckId = $("#txtTruckId").val();
var truckReg = $("#txtTruckReg").val();
var description = $("#txtDescription").val();
var condition = $("#txtCondition").val();
var data = '{"obj":{"TruckId":"' + truckId + '","Reg":"' + truckReg +
'","Description":"' + description + '","Condition":"' + condition + '"}}';
var json = JSON.stringify(data)
$.ajax({
url: '/api/Values',
cache: false,
type: 'POST',
data: json,
dataType: 'json',
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
})
}
When I debug that the 'data' variable successfully captures the data.
I then have a function in my WebApi controller ...
// POST api/values
public void Post(TruckInfo obj)
{
WebApiTestEntities db = new WebApiTestEntities();
db.TruckInfoes.Add(obj);
db.SaveChanges();
}
However, when I debug thst all of the parameters are showing a null value.
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but that hasn't worked.
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
I also found this which kind of comes up with an answer but after trying to alter my code so it looks like the code they have written it still doesn't work.
jQuery posts null instead of JSON to ASP.NET Web API
Is any one able to help?
Thanks in advance
Lex
Start by fixing your JSON:
var data = {
truckId: truckId,
reg: truckReg,
description: description,
condition: condition
};
var json = JSON.stringify(data);
and then make sure you specify the correct content type request header:
$.ajax({
url: '/api/Values',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: json,
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
});
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but
that hasn't worked.
No, no, no. Not necessary as long as you format properly your JSON request, the Web API will bind it to your model.

Passing unstructured JSON between jQuery and MVC Controller Actions

There is quite a lot of helpful information on MVC model binding.
My problem stems from the fact that I am trying to avoid creating strongly typed data in my MVC application as it mostly needs to act as a data router.
Basically, I have a set of fields on a page, with a class 'input', that I can gather with jQuery('.input'), iterate over and stuff into a javascript object. I then send this to my ASP.NET MVC controller:
var inputData = my_serialize( $('input');
$.ajax({
type:'POST',
url: '/acme/Ajax/CaptureInput',
dataType: "json",
data: { inputData: JSON.stringify(inputData) },
success: Page_Response_RegisterAndDeposit,
error: Page_AjaxError
});
On the C# side, I have
public JsonResult CaptureInput(string inputDataAsJsonString)
{
JavaScriptSerializer JSON = new JavaScriptSerializer();
object inputData = JSON.DeserializeObject(inputDataAsJsonString);
This seems like a wasteful level of indirection, I'd prefer to pass the data as contentType:application/json and have CaptureInput accept an object or IDictionary or even a dynamic.
You could use the serializeArray method. Let's suppose that you have a form containing the input elements which could be of any type and you want to invoke the following controller action:
public ActionResult CaptureInput(Dictionary<string, string> values)
{
...
}
here's how you could proceed:
<script type="text/javascript">
var values = $('form').serializeArray();
var data = {};
$.each(values, function (index, value) {
data['[' + index + '].key'] = value.name;
data['[' + index + '].value'] = value.value;
});
$.ajax({
url: '#Url.Action("CaptureInput")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
alert('success');
}
});
</script>
Not exactly what you're after but maybe the resolution of this issue would give you a partial workaround, by allowing you to bind to a simple wrapper object with an embedded Dictionary. It might even allow binding direct to a Dictionary. Not sure...
You might also need to explicitly set the json ContentType header in your $.ajax call
"JSON model binding for IDictionary<> in ASP.NET MVC/WebAPI"

unable to pass post value over from ajax to the page in .net c#

Does anyone know what is it going on here? I have try to pass a value from ajax to .aspx, but somehow the value seem doesn't pass over successfully.
Following is my code:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: "sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
and this is my code inside my .net c#:
newTest.Value = Request.QueryString["sState"];
Somehow the for Request.QueryString["sState"] is empty in .net c#. Does anyone know what is going wrong here ?
When passing data in POST, the data is not passed in Request.QueryString, it's passed into Request.Form instead. Try
newTest.Value = Request.Form["sState"];
Another thing I'd change is the jQuery call - use a data object instead of just a string, a such:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: { sState: "VIC" },
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Request.QueryString is for GET requests only. For POST requests, you need Request.Form. See also: Get POST data in C#/ASP.NET
You need to use GET request as it is light in nature but less secured too and it is passed in querystring.:
$.ajax({
type: "GET",
url: "pgtest.aspx?sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Now you will get below values:
newTest.Value = Request.QueryString["sState"];

Categories