DataTables Editor In MVC - visual-studio

I want to use DataTables Editor but I want full control over the post back rather than letting Editor-Server handle it. Is there a way to do this? I am able to specifiy the url in Ajax on the client side and it does post back to the Controller, the only problem is I cannot figure how to get the data out of the call.
This is the Ajax portion:
$(document).ready(function () {
editor = new $.fn.dataTable.Editor({
ajax: ({
url: "/../AnyController/Update",
dataType: "json",
contentType: "application/json",
type: 'POST'
}),
formOptions: {
inline: {
onBlur: true,
submit: 'all'
}
},
table: "#timetracker",
fields: [
{
label: "Date1:",
name: "Date1"
},
{
label: "Comment 1:",
name: "Comment1",
type: "textarea"
}
]
});
And this is the Contoller method:
[HttpPost]
public JsonResult Update(EditorReturnData wtd)
{
return Json(wtd);
}
I have tried using a variety of other method signatures but the value of wtd is always null. I have no problem loading the table just by passing Json data, but how to takeover the update process from datatables editor is eluding me.
I have one update. I could not figure out how the Get, Post and Put could all use the same Controller Method and the method takes no parameters, even for the Post and Put. Finally I figured out that Editor is passing the data in the Header and it could be accessed with Request.Body. From there it must be the Datatables dll that is doing the actual updates.

enter code hereI have found the best way to do this is to post back from ajax to a different Controller for Post and Put and you can get access to the return data from the HttpRequest body in the following manner.
public ActionResult Rest(HttpRequest request)
{
var stream = request.Body;
string url = new StreamReader(stream).ReadToEnd();
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
I added this code to the RestController from the Datatables Dot Net Core Demo Rest example which can be downloaded from https://editor.datatables.net/
The Ajax looks like this
editor = new $.fn.dataTable.Editor( {
ajax: {
create: {
type: 'POST',
url: '/api/rest/create'
},
edit: {
type: 'PUT',
url: '/api/rest/edit'
},
remove: {
type: 'DELETE',
url: '/api/rest/remove'
}
},

Related

ASP.NET Core 2.2 Razor Pages - AJAX Call to page model not returning data

I am new to AJAX and cant even get the basics to function correctly.
I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.
The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.
Razor Page:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Page Model:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
Below is the code that is now working for me. Thanks for everyone's input.
Razor Page (script section):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
Page model:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}

can't get to web api controller action with jquery ajax post

I'm trying to create my first REST application with the web api in mvc4. I have a controller set up with the HttpPost verb but for some reason when I click the link to post the xml string to the controller I get an error - "{"Message":"No HTTP resource was found that matches the request URI '/api/Apply/ApplyToJob'.","MessageDetail":"No action was found on the controller 'Apply' that matches the request."}" Any ideas what I might be doing wrong? Here's the view page...
Post Data
<script type="text/javascript">
window.onload = function () {
$("#lnkPost").on("click", function () {
$.get("/TestResponse.xml", function (d) {
$.ajax({
//contentType: "text/xml",
//dataType: "xml",
type: "post",
url: "/api/Apply/ApplyToJob",
data: {
"strXml": (new XMLSerializer()).serializeToString(d)
},
success: function () { console.log('success'); }
});
});
});
};
</script>
and here's the controller.
public class ApplyController : ApiController
{
[HttpPost]
[ActionName("ApplyToJob")]
public string ApplyToJob(string strXml)
{
return "success";
}
}
Modify your action's parameter like below:
public string ApplyToJob([FromBody]string strXml)
This is because without this FromBody attribute, the string parameter is expected to come from the Uri. Since you do not have it in the Uri the action selection is failing.
Also, looking at your client code, shouldn't you set the appropriate content type header in your request?
Edited:
You can modify your javascript to like below and see if it works:
$.ajax({ contentType: "text/xml",
dataType: "xml",
type: "post",
url: "/api/values",
data: "your raw xml data here",
success: function () { console.log('success'); }
});

How to call partial view through ajax in mvc3

I need to call a partial view through ajax. I have tried the following, but I am not sure how to complete it.
$("#UserName").change(function () {
var userid = $("#UserName").val();
var ProvincialStateID = $("#State").val();
var Hobbyid = $("#Hobby").val();
var Districtid = $("#DistrictNames").val();
var Homeid = $("#Hobbyhome_EstablishmentId").val();
var urlperson = '#Url.Action("FetchPersonByUserName")';
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
//Dont know what to write here
});
});
Here is the function that I have written in my Controller:
[HttpPost]
public ActionResult FetchPersonByUserName(int userid,int stateid,int districtid,int homeid,int Hobbyid)
{
//Code to fetch the data in the partial using all parameters
return PartialView("_LearnerAssociationGridPartial", list);
}
When I click on a dropdown the ajax gets called and I want the function which is called through ajax to redirect it to the partial view. Please help me because currently I am not able to display my partial view
What you need is something like
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid,
stateid: ProvincialStateID,
hobbyid: Hobbyid,
districtid: Districtid,
homeid: Homeid },
success: function (data) {
var result = data;
$('targetLocation').html(result);
}
});
it is recomended to not use data straight from variable but you can.
Now target location is where you want the result to be displayed to.
See more information in here:
http://api.jquery.com/jQuery.ajax/
As to slow fetching data, try optimalize your query
Update
For nhibernate running slow, try http://www.hibernatingrhinos.com/products/nhprof which is nhibernate profiler, for paid version, or try sql profiler to see what is query is beeing executed, often you can get much more that you would expect and or really slow query due to complexity of the query.
I dont understand what you mean by redirect to the parial view. Usually people use ajax and Partial views to get part of a page without a page refresh ( you might have seen this kind of behaviour in this site/facebook/twitter etc..) So i guess you probably want to show the data you are fetching asynchronosly to be shown in a part of your current page. you can do that in your success handler
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
$("#divUserInfo".html(data);
}
});
Assumung you have a div with id divUserInfo in your current page.
If you really want to redirect after the ajax post, you can do it like this.
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
window.location.href="Why-I-need-Ajax-Then.php";
}
});
Personally, I dont use HttpPost (both in client and server) If it is a method to GET some data. I simpy use the jquery get or load.
$.get("yourUrl", { userid: userid, stateid: ProvincialStateID } ,function(data){
$("#divUserInfo".html(data);
});

MooTools: How do package data for a POST ajax request?

I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request

How to filter occupation as you type in MVC3

I have a list of 2500 occupations held in our db. On our site we ask for you to enter your occupation and I would like it to filter the results as they type; like Play.com's search. Is there a way to do this in MVC3?
Appreciate any help.
You can do this using a autocomplete javascript.
For example:
http://www.pnpguidance.net/post/jQueryAutoCompleteASPNETMVCFramework.aspx
You can grab your data using jQuery Ajax.
I would create an action method that would return JSON:
[HttpGet()]
public JsonResult Occupations(String searchCriteria)
{
String[] occupations = new String[] { "Lawyer", "Carpenter" };
return Json(occupations.Where(s => s.Contains(searchCriteria))
.ToList(), JsonRequestBehavior.AllowGet);
}
If you run a GET request on this link: /Occupations?searchCriteria=Carpenter you'll receive ["Carpenter"] in a response.
I would make a jQuery ajax call to this action method. On success, I would take a reponse and generate an output such as list of li elements to select from.
Example of an ajax json get request is below:
$.ajax({
type: 'json',
url: '/Occupations',
type: 'GET',
cache: false,
data: { searchCriteria: searchCriteria},
error: function () {
},
success: function (result) {
alert(result);
}
});
This is from a notepad, so there might be some minor syntax errors.

Resources