Call Asp.Net MVC action to load store in sencha touch - asp.net-mvc-3

I am calling asp.net action from proxy to fill the store data.
I am specifying the url correctly but on make get request to Action it is appending query string params to the call. This is resulting in 404 error.
I am posting my code below,
Asp.net mvc Action
public JsonResult SongsList()
{
List<MusicFileModel> musicFileModels = MusicFileModel.GetAllMusicFiles();
return Json(musicFileModels, JsonRequestBehavior.AllowGet);
}
Store definition in Sencha Touch 2
Ext.define('CloudPlayerUI.store.Songs', {
extend: 'Ext.data.Store',
config: {
model:'CloudPlayerUI.model.song',
proxy: {
type: 'ajax',
url: '/Home/SongsList',
param:'',
reader: {
type: 'json'
}
},
autoLoad:true
}
});
This is the ajax call that is made.
GET http://localhost/Home/SongsList?_dc=1333338051329&page=1&start=0&limit=25
I am assuming that because, Action doesn't have any params which is being made my ajax call
it is resulting in an 404 error.
I am not sure the correct way of calling mvc action. Please let me know if I am going wrong.
Any help is appreciated.
update:
I tried adding the same query string params to asp.net mvc action. Still it is causing 404 error. When I open the same url without any query string params in new tab it is returning me Json result.

I figured out the issue.
The 404 error was due to incorrect URL config param defined in the store. Also I added a rootProperty to reader.
This is how the proxy code looks like.
Ext.define('CloudPlayerUI.store.Songs', {
extend: 'Ext.data.Store',
config: {
model:'CloudPlayerUI.model.song',
proxy: {
url: 'Home/SongsList', //Changes to url
type:'ajax',
reader: {
type: 'json',
rootProperty: 'ResponseData' //Addeed reader property.
}
},
autoLoad:true }
});
Constructing return object in Asp.MVC action.
var results = new
{
Success = true,
ResponseData = musicFileModels
};
return Json(results, JsonRequestBehavior.AllowGet);

Related

How to pass Ajax params to controller in ASP.NET Core

I created a select with select2 js and created the ajax request:
$('#slcCidade').select2({
ajax: {
type:'POST',
url: '/get-cidade',
minimumInputLength: 3,
data: function (params) {
var query = {
search: params.term
}
return query;
},
processResults: function (data) {
return {
results: data.items
};
}
}
});
In my controller I have the following method to get data, then it returns to my page:
[Route("get-cidade/{search:regex(^[[a-zA-Z]])}")]
[HttpPost]
public async Task<JsonResult> GetCidade(string search)
{
var lstCidadesVM = _mapper.Map<IEnumerable<CidadeViewModel>>(await _cidadeBLL.GetByNome(search));
return new JsonResult(new { Data = lstCidadesVM });
}
The request never returns to my controller and analyzing the request I see that a 404 error has occurred
Request URL: https://localhost:44394/get-cidade?search=curvelo
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:44394
Referrer Policy: no-referrer-when-downgrade
Where am I doing wrong? I just need to call the method from my controller by entering the search term via AJAX.
Thanks!
I think the route you're implementing is mostly '/get-cidade/curvelo',without any data to transfer as parameter.
Select2 settings were correct, the problem was the GetCity method route in the controller, it just worked by removing {search:regex(^[[a-zA-Z]])} of the route. The method went like this:
[Route("get-cidade")]
public async Task<JsonResult> GetCidade(string search)
{
var lstCidadesVM = _mapper.Map<IEnumerable<CidadeViewModel>>(await _cidadeBLL.GetByNome(search));
return new JsonResult(new { Data = lstCidadesVM });
}

DataTables Editor In MVC

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'
}
},

Spring MVC using AJAX return page not found

I have create an endpoint to delete a record, yet when i use either POST or GET, i could not reach to that end point, it always said page not found ,i realized there is weird parameter was appended.
example:
http://localhost:8080/admin/panel/case/survey/delete/completion/form/0af9518a-8eea-4e69-94a3-3571c3785215?_=1526048495480
this my end point :
#RequestMapping(value = "/delete/completion/form/${id}", method = RequestMethod.GET)
#ResponseBody
public String deleteCompletionForm(#PathVariable("id") String id) {
return String.valueOf(completionFormService.deleteCompletionFormThenLog(id));
}
this is my ajax :
$('table').on('click', '.delete', function () {
if (confirm('Are you sure you want to remove this record!')) {
var contentPanelId = jQuery(this).attr("id");
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/admin/panel/case/survey/delete/completion/form/" + contentPanelId,
cache: false,
timeout: 600000,
success: function (data) {
if (data) {
$(this).parents('tr').remove();
}
},
error: function (e) {
alert("Can not delete the record, please try again!")
}
});
}
});
It is happening due the cache setting you are specifying which will add a timestamp parameter to the URL.
From the Jquery docs (https://api.jquery.com/jQuery.ajax/):
cache (default: true, false for dataType 'script' and 'jsonp')
Type:
Boolean If set to false, it will force requested pages not to be
cached by the browser. Note: Setting cache to false will only work
correctly with HEAD and GET requests. It works by appending
"_={timestamp}" to the GET parameters. The parameter is not needed for
other types of requests, except in IE8 when a POST is made to a URL
that has already been requested by a GET.

Using AJAX with MVC 5 and Umbraco

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

No 'MediaTypeFormatter' is available to read an object of type 'String'

I'm using the ASP.NET Web API. I have an action in my controller which works fine if there's no parameter. If there is a parameter, like:
public string UploadFile(string actionType)
then my action isn't called and I get the following message, viewed in Fiddler:
No 'MediaTypeFormatter' is available to read an object of type 'String' with the media type 'multipart/form-data'
The route in my global.asx is as follows:
"api/{controller}/{action}/{actionType}"
I'm using Jquery Post to call the action:
function upload() {
var actiontype = $("input:radio[name=actiontype]").val();
var formData = new FormData($('form')[0]);
$.ajax({
url: 'api/uploads/uploadfile/' + actiontype,
type: 'POST',
success: function (data) {
$("#mydiv").append(data);
},
error: function (data) {
$("#mydiv").append(data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
};
Here's my action method:
public string UploadFile(string actionType)
{
if (Request.Content.IsMimeMultipartContent())
{
//Save file
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/Files"));
Request.Content.ReadAsMultipartAsync(provider);
}
return string.Format("Action {0} Complete!", actionType);
}
Is this a known problem, with a workaround? How can I have a simple action with parameter?
Assuming you're using the default routes, it looks like you're posting to an incorrect path. This is a common confusion that MVC developers seem to encounter (i know i did). MVC uses a default path like: /Controller/Action.
In web API's default routing setup, however, the action name is skipped (/api/Controller) then the method is found through the intersection of the HTTP verb name (post), the method name (Post___) and parameter if necessary.
Assuming you have an API controller named Uploads, you should have an action named PostUploadFile.
$.ajax({
url: 'api/uploads/',
type: 'POST',
Some things to notice...
I started the name of your action with the text "Post..." this matters, the remainder of the name does not
Your post url was shorted to the name of the controller.
I went more in depth explaining the mapping here.
EDIT
Apparently your experiencing an odity of WebAPI. The way around this is to stuff your "actionType" parameter into a simple object, so model binding can take over.
Rick Strahl explains this and some other binding oddities here. There is also another SO question addressing similar issues.

Resources