return partial view from async method - ajax

I've an async action method that return a partial view.
this action method called from a function with ajax.
my problem : when this method invoked every thing looks good except returned partial view.
I got error 500.
this is my action method Code :
[HttpPost]
public async Task<ActionResult> ChangeStateGroup(int[] lstCustomerServiceId, int newState)
{
int _counter = 0;
try
{
var _isOk = await CommonFunctions.ChangeState(_customerServiceId, _stateId, string.Empty);
if (_isOk)
{
//------do somthing
}
}
TempData[MyAlerts.SUCCESS] = string.Format("succeed Operation {0}", _counter);
}
catch (Exception ex)
{
TempData[MyAlerts.ERROR] = string.Format("Error: {0}", ex.Message);
}
return PartialView("_AlertsPartial");
}
and this is my jquery Code:
function postCustomerChangeStateGroup(lstCustomersId) {
var arrCustomersId = lstCustomersId.split(',');
$.ajax({
type: "POST",
url: "../Customer/ChangeStateGroup",
data: {
lstCustomerServiceId: arrCustomersId,
newState: $("#fk_state").val()
},
success: function (data) {
if (data.indexOf("error") !== -1) {
$("#inlineAlert_Wrapper").append(data);
}
else {
getCustomerReport();
$('#modal-container').modal('toggle');
$("#alert_Wrapper").append(data);
}
},
failure: function (errMsg) {
alert("An Error Accoured: " + errMsg);
}
});
}

Partial views cannot be asynchronous in ASP.NET pre-Core. You can have asynchronous partial views in ASP.NET Core.
So, your options are:
Update to ASP.NET Core.
Remove the asynchronous code and make it synchronous instead.

Error 500 means the error inside of the action.It maybe because ot the empty input parameters. Check them in debugger and if they are empty,
try to use application/json content type,sometimes it works better
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Customer/ChangeStateGroup",
data: JSON.stringify( {
lstCustomerServiceId: arrCustomersId,
newState: $("#fk_state").val()
}),
success: function (data) {
....
create viewModel
public class ViewModel
{
public int[] lstCustomerServiceId {get; set;}
public int newState {get; set;}
}
and fix the action
public async Task<ActionResult> ChangeStateGroup([FromBody] ViewModel model)

Related

Session not retaining TempData through multiple Ajax calls to Controller

Im trying to work with an object (VideoInfo) in several Action methods. A form sends a viewmodel with a video file to the Upload method in VideoController. It uploads the video and returns a generated guid. When the callback has returned, a new ajax call is made to the Convert method which returns the guid. As seen in the javascript part of Create.cshtml it makes two other Ajax calls, one to the Progress method and one to the Azure method.
When trying to fetch the VideoInfo object in the Azure method and the Progress method, videoInfo is null. Though it successfully retains the data between the Upload method and Convert method. Im using TempData.Peek() so that it shouldnt mark it for deletion.
I can see that the Upload and Convert method is using the same instance of VideoController, where as the Progress and Azure method uses another instance, I guess this could have to do with the problem.
InstanceId when running Upload method: 23ef96fa-c746-4722-ad07-e9e40fc95f29
InstanceId when running Convert method: 23ef96fa-c746-4722-ad07-e9e40fc95f29
InstanceId when running Progress method: 0aba24b2-ccb8-434d-a27d-cc66cb52c466
InstanceId when running Azure method: 0aba24b2-ccb8-434d-a27d-cc66cb52c466
How can I retain data between my Ajax calls in the VideoController?
Why is the instance id same for the first two calls but then it changes?
VideoController.cs
using System;
namespace MediaPortal.Controllers
{
[Authorize(Roles = "Admin")]
public class VideoController : Controller
{
private static Guid InstanceId { get; }
static VideoController()
{
InstanceId = Guid.NewGuid();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(CreateVideoViewModel model)
{
if (ModelState.IsValid)
{
if (model.File != null)
{
Debug.WriteLine("Upload method InstanceId: " + InstanceId.ToString());
// ...
TempData[videoInfo.Id] = videoInfo;
videoInfo.cvvm.File.SaveAs(videoInfo.TempPath);
return Json(new { Successfull = true, Id = videoInfo.Id });
}
return null;
}
return null;
}
[HttpPost]
public ActionResult Convert(string id)
{
Debug.WriteLine("Convert method InstanceId: " + InstanceId.ToString());
// Create new object of FFMpegConvertor
var converter = new FFMpegConverter();
VideoInfo videoInfo = (VideoInfo)TempData.Peek(id);
// ...
return Json(new { Successfull = true, Id = videoInfo.Id });
}
[HttpPost]
public ActionResult Azure(string id)
{
Debug.WriteLine("Azure method InstanceId: " + InstanceId.ToString());
VideoInfo videoInfo = (VideoInfo)TempData[id];
// ...
if (videoUpload != null && thumbnailUpload != null)
{
Video video = new Video
{
Id = videoInfo.Id.ToString(),
Name = videoInfo.cvvm.Name,
ProjectId = videoInfo.cvvm.ProjectId,
Type = "mp4",
VideoUri = videoUpload.Uri.ToString(),
ThumbnailUri = thumbnailUpload.Uri.ToString()
};
db.Videos.Add(video);
db.SaveChanges();
return Json(new { Successful = true, Data = Url.Action("Index", new { projectId = videoInfo.cvvm.ProjectId }) });
}
return null;
}
[HttpPost]
public JsonResult Progress(string id)
{
Debug.WriteLine("Progress method InstanceId: " + InstanceId.ToString());
try
{
VideoInfo videoInfo = (VideoInfo)TempData.Peek(id);
return Json(new { Data = videoInfo.Progress });
}
catch
{
return Json(new { Data = "No Video Information in Dictionary for Id: " + id });
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Create.cshtml (JQuery/Ajax)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$.noConflict();
jQuery(document).ready(function ($) {
var bar = $('.progress-bar');
var percent = $('.percent');
$('#Myform').ajaxForm({
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function (uploadStatus) {
console.log("Upload finished for video with Id: " + JSON.parse(uploadStatus.responseText).Id);
setTimeout(function () { progress(uploadStatus) }, 1000);
$.ajax({
type: "POST",
url: '#Url.Action("Convert", "Video")?id=' + JSON.parse(uploadStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (convertStatus) {
console.log("Conversion finished for video with Id: " + JSON.parse(convertStatus.responseText).Id);
$.ajax({
type: "POST",
url: '#Url.Action("Azure", "Video")?id=' + JSON.parse(convertStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (azureStatus) {
window.location.href = JSON.parse(azureStatus.responseText).Data;
}
});
}
});
}
});
function progress(uploadStatus) {
$.ajax({
type: "POST",
url: '#Url.Action("Progress", "Video")?id=' + JSON.parse(uploadStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (progressStatus) {
console.log("Progress: " + JSON.parse(progressStatus.responseText).Data);
if (JSON.parse(progressStatus.responseText).Data < 100) {
setTimeout(function () { progress(uploadStatus) }, 1000);
}
else if (JSON.parse(progressStatus.responseText).Data >= 100) {
console.log("Video Conversion Completed");
}
else {
console.log("Something went wrong");
}
}
})
}
});
</script>
It seems IIS Express was the problem. I cant say why though. I realized this because when I deployed the project to my production server in Azure it all worked fine.
So instead of using IIS Express I installed IIS on my development machine, works perfectly after that.

jqueryui autocomplete render HTML returned by server

I have a simple page with an input text-box. The text box is bound to jquery ui autocomplete that makes an AJAX call to the server. My server side code is an ASP.NET MVC site. The only difference I have as compared to most examples found over the Internet is that my Server side code returns a PartialView (html code) as results instead of JSON. I see the AJAX call happening and I see the HTML response in the AJAX success event as well.
My question is how do I bind this HTML data to show in the AutoComplete?
The code I have so far is:
$("#quick_search_text").autocomplete({
minLength: 3,
html: true,
autoFocus: true,
source: function (request, response) {
$.ajax({
type: "POST",
url: "serversideurl",
data: "{ 'SearchTerm': '" + request.term + "', 'SearchCategory': '" + $("#quick_search_category").val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
},
success: function (data) {
//THIS IS WHERE MY HTML IS RETURNED FROM SERVER SIDE
//HOW DO I BIND THIS TO JQUERY UI AUTOCOMPLETE
}
});
},
select: function (event, ui) {
},
response: function (event, ui) {
console.log(ui);
console.log(event);
}
});
This works:
1) Create an action in your controller and set the RouteConfig to start this action
public class HomeController : Controller
{
public ActionResult Index20()
{
MyViewModel m = new MyViewModel();
return View(m);
}
Create a view without any type of master page
Add this view model:
public class MyViewModel
{
public string SourceCaseNumber { get; set; }
}
Go to Manage Nuget Packages or PM Console and add to MVC 5 project - Typeahead.js for MVC 5 Models by Tim Wilson
Change the namespace for the added HtmlHelpers.cs to System.Web.Mvc.Html and rebuild
Add this class:
public class CasesNorm
{
public string SCN { get; set; }
}
Add these methods to your controller:
private List<Autocomplete> _AutocompleteSourceCaseNumber(string query)
{
List<Autocomplete> sourceCaseNumbers = new List<Autocomplete>();
try
{
//You will goto your Database for CasesNorm, but if will doit shorthand here
//var results = db.CasesNorms.Where(p => p.SourceCaseNumber.Contains(query)).
// GroupBy(item => new { SCN = item.SourceCaseNumber }).
// Select(group => new { SCN = group.Key.SCN }).
// OrderBy(item => item.SCN).
// Take(10).ToList(); //take 10 is important
CasesNorm c1 = new CasesNorm { SCN = "11111111"};
CasesNorm c2 = new CasesNorm { SCN = "22222222"};
IList<CasesNorm> aList = new List<CasesNorm>();
aList.Add(c1);
aList.Add(c2);
var results = aList;
foreach (var r in results)
{
// create objects
Autocomplete sourceCaseNumber = new Autocomplete();
sourceCaseNumber.Name = string.Format("{0}", r.SCN);
sourceCaseNumber.Id = Int32.Parse(r.SCN);
sourceCaseNumbers.Add(sourceCaseNumber);
}
}
catch (EntityCommandExecutionException eceex)
{
if (eceex.InnerException != null)
{
throw eceex.InnerException;
}
throw;
}
catch
{
throw;
}
return sourceCaseNumbers;
}
public ActionResult AutocompleteSourceCaseNumber(string query)
{
return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
}
credit goes to http://timdwilson.github.io/typeahead-mvc-model/

Setting up .Net MVC http error codes for ajax calls

I'm trying to setup my controllers so that they can use http error codes to send the responses to ajax calls. So for example I have my login ajax call and controller action:
[System.Web.Mvc.HttpPost, System.Web.Mvc.AllowAnonymous]
public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
{
[...]
var loginError = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Lorem ipsum 2 " + ErrorMessages.LOGINERROR),
ReasonPhrase = "Lorem ipsum 2 " + ErrorMessages.LOGINERROR
};
throw new HttpResponseException(loginError);
}
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "text",
success: callBack,
error: function () { console.log("Error..."); },
statusCode : {
401: function (result) {
console.log("Login failed (401): " + result);
}
}
});
I'm thinking there are a couple of things I'm not doing right, if someone can point them out that would be lovely!
Thanks!
Look at this solution: ASP.NET MVC Ajax Error handling
Darin Dimitrov write very nice solutions with action filter:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
Then you could write your client error handling for all status codes and use it for ajax requests.
Instead of throw exception just return ActionResult that provide some content and setup response code. For your case you can create something that I call ExtendedJsonResult:
public class ExtendedJsonResult : JsonResult
{
public ExtendedJsonResult(object data)
{
base.Data = data;
}
public int StatusCode { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = this.StatusCode;
base.ExecuteResult(context);
}
}
and then in controller
return new ExtendedJsonResult("Some error")
{
StatusCode = 401,
};
You can also just return existing HttpStatusCodeResult.

To what mvc object do I bind this kind of javascript array?

I am populating an array with an [int,bool]:
$.each(ownedChecked, function (key, val) {
/*code to set id as int and paintedTrue as bool*/
ownedIDs.push([id,paintedTrue]);
});
I create a var that will be stringified:
var saveData = { OwnedListEntryIDs:ownedIDs };
//send data
$.ajax({
url: '/ListEntry/OwnedModels',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(saveData),
success: function (data) { alert('Update success: ' + data); },
failure: function (data) { alert('Update failed: ' + data); }
});
Here is the ViewModel:
public class OwnedPaintedSave
{
//collection contains a ListEntryID and a bool indicating whether it is painted or not
public Dictionary<int,bool> OwnedListEntryIDs { get; set; }
}
Once in the controller method, ModelState.Isvalid passes and code gets to the foreach loop, but models is always NULL:
[HttpPost]
public JsonResult OwnedModels(OwnedPaintedSave models)
{
if (ModelState.IsValid)
{
foreach (var id in models.OwnedListEntryIDs)
{ }
}
}
I tried setting traditional:true in the $.ajax method, but same issue. I'm guessing the Dictionary in the ViewModel is not what I need to bind to, but I'm not sure what it should be. Thanks for any help.
I gave the OwnedPaintedSave object two int[] properties, one for OwnedIDs and one for PaintedIDs.
I think the problem lies in your controller. You are passing var saveData = { OwnedListEntryIDs:ownedIDs }; (essentially a Dictionary<int, bool> - yes?) as your data but the parameter in the action result is of type OwnedPaintedSave
I think if you change your controller parameter to Dictionary<int, bool> ownedListEntryIDs and don't stringify the javascript object, the framework is clever enough to serialize and deserialize your object. So you would have this...
var saveData = { OwnedListEntryIDs:ownedIDs };
//send data
$.ajax({
url: '/ListEntry/OwnedModels',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: saveData,
success: function (data) { alert('Update success: ' + data); },
failure: function (data) { alert('Update failed: ' + data); }
});
And then this in your controller...
[HttpPost]
public JsonResult OwnedModels(Dictionary<int, bool> ownedListEntryIDs)
{
if (ModelState.IsValid)
{
foreach (var id in ownedListEntryIDs)
{ }
}
}

Model Binding and posting form via ajax

I want to post a form via ajax call also model will be passed into the action method, but want to get Model errors via json. How can I do this?
You could write a custom action filter:
public class HandleJsonErrors : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = (filterContext.Controller as Controller).ModelState;
if (!modelState.IsValid)
{
// if the model is not valid prepare some JSON response
// including the modelstate errors and cancel the execution
// of the action.
// TODO: This JSON could be further flattened/simplified
var errors = modelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new
{
x.Key,
x.Value.Errors
});
filterContext.Result = new JsonResult
{
Data = new { isvalid = false, errors = errors }
};
}
}
}
and then put it into action.
Model:
public class MyViewModel
{
[StringLength(10, MinimumLength = 5)]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[HandleJsonErrors]
public ActionResult Index(MyViewModel model)
{
// if you get this far the model was valid => process it
// and return some result
return Json(new { isvalid = true, success = "ok" });
}
}
and finally the request:
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
foo: 'abc'
}),
success: function (result) {
if (!result.isvalid) {
alert(result.errors[0].Errors[0].ErrorMessage);
} else {
alert(result.success);
}
}
});
Something like this?
$.ajax({
type: "POST",
url: $('#dialogform form').attr("action"),
data: $('#dialogform form').serialize(),
success: function (data) {
if(data.Success){
log.info("Successfully saved");
window.close();
}
else {
log.error("Save failed");
alert(data.ErrorMessage);
},
error: function(data){
alert("Error");
}
});
[HttpPost]
public JsonResult SaveServiceReport(Model model)
{
try
{
//
}
catch(Exception ex)
{
return Json(new AdminResponse { Success = false, ErrorMessage = "Failed" }, JsonRequestBehavior.AllowGet);
}

Resources