Unable to send data from actionResult to asyn mothod in mvc - asp.net-mvc

This is my controller actionReslt
[ValidateAntiForgeryToken()]
public ActionResult PaymentDetails(PaymentViewModel payment)
{
PaymentModel paymentModel = new PaymentModel();
// AutoMapper.Mapper.CreateMap<PaymentModel, PaymentViewModel>();
if (ModelState.IsValid)
{
CreditCardDetailsModel creditCardDetailsModel = new CreditCardDetailsModel();
creditCardDetailsModel.SecurityId = payment.SecurityId;
creditCardDetailsModel.ExpiryDate = payment.Month + payment.Year;
creditCardDetailsModel.CardNumber = payment.CardNumber;
paymentModel.CreditCardDetails = creditCardDetailsModel;
return RedirectToAction("Payment",paymentModel);
}
return View("FlightBooking");
}
and this is my async method
public async Task<JsonResult> Payment(PaymentModel model)
{
CreateFormOfPaymentReplyModel response = new CreateFormOfPaymentReplyModel();
resource = Constants.Payment;
response = await Post<CreateFormOfPaymentReplyModel>(model);
resource = Constants.PnrConfirm;
var pnrConformStatus = await Get<PNRConfirmResponseModel>();
return new JsonResult { Data = new { status = false, message = response } };
}
and i want to return to Payment method with paymentObject if it is valid but PaymentModel is returning null data and it is showing the error as
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet

Have you tried passing allowget to your return variable?
i.e:
return Json( new { status = false, message = response }, JsonRequestBehavior.AllowGet);
Hope this helps.

Related

ASP.NET MVC Controller cannot return HttpResponseMessage correctly with streamed content

Just as the title says I am not getting the MVC Controller to return HttpResponseMessage correctly.
[HttpGet]
[AllowAnonymous]
public HttpResponseMessage GetDataAsJsonStream()
{
object returnObj = new
{
Name = "Alice",
Age = 23,
Pets = new List<string> { "Fido", "Polly", "Spot" }
};
var response = Request.CreateResponse(HttpStatusCode.OK);
var stream = new MemoryStream().SerializeJson(returnObj);
stream.Position = 0;
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return response;
}
This is what I got using MVC Controller:
It works fine when using WebApi ApiController
Correct me if I'm wrong I think the problem is MVC is serializing HttpResponseMessage instead of returning it.
By the way I am using MVC 5.
Thanks in advance.
EDIT
I would like to have the flexibility to write to the response stream directly when returning large datasets.
Perhaps try returning an ActionResult from your MVC method instead.
public ActionResult GetDataAsJsonStream() {}
In order to return a stream, you'll likely have to use FileStreamResult. What would be even easier is just returning a JsonResult.
public ActionResult GetDataAsJson()
{
object returnObj = new
{
Name = "Alice",
Age = 23,
Pets = new List<string> { "Fido", "Polly", "Spot" }
};
return Json(returnObj, JsonRequestBehavior.AllowGet);
}
This is pseudo code but the concept should be sound.
Thanks to Phil I got it to work by having the MVC controller return FileStreamResult.
Here is the code
public ActionResult GetDataAsJsonStream()
{
object returnObj = new
{
Name = "Alice",
Age = 23,
Pets = new List<string> { "Fido", "Polly", "Spot" }
};
var stream = new MemoryStream().SerializeJson(returnObj);
stream.Position = 0;
return File(stream, "application/json");
}
UPDATE
A better way to do this is to write directly to the response stream without creating a memory stream
public ActionResult GetJsonStreamWrittenToResponseStream()
{
object returnObj = new
{
Name = "Alice",
Age = 23,
Pets = new List<string> { "Fido", "Polly", "Spot" }
};
Response.ContentType = "application/json";
Response.OutputStream.SerializeJson(returnObj);
return new EmptyResult();
}

Call async Task<> from controller in ASP.NET MVC

I have a Library wrapper OVH API and i try to call a function for get my consumer key in a ASP.NET MVC project. It works in a Console project application but the method never response in my Controller : the method in the Library
public async Task<CredentialsResponse> RequestCredential(IEnumerable<AccessRule> accessRules, string redirectUrl = null)
{
Ensure.NotNull("accessRules", accessRules);
CredentialsRequest cmd = new CredentialsRequest();
cmd.AccessRules.AddRange(accessRules);
cmd.Redirection = redirectUrl;
if (cmd.AccessRules.Count == 0)
throw new ArgumentException("You must specify at least one accessRule");
return await RawCall<CredentialsResponse>(HttpMethod.Post, "/auth/credential", cmd;
}
and i call in the controller :
public ActionResult Index()
{
Information infosClient = new Information();
OvhApiClient api = new OvhApiClient("", "", OvhInfra.Europe);
CredentialsResponse response = api.RequestCredential(new[]{
new AccessRule{ Method = "GET", Path = "/*"},
new AccessRule{ Method = "PUT", Path = "/*"},
new AccessRule{ Method = "POST", Path = "/*"},
//new AccessRule{ Method = "DELETE", Path = "/*"},
}).Result;
api.ConsumerKey = response.ConsumerKey;
infosClient.ConsumerKey = api.ConsumerKey;
return View(infosClient);
}
I already tried quite a lot of things without success (put the call in a method async for example).
Thanks in advance for your help
Make the controller action async:
public async Task<ActionResult> Index()
{
...
CredentialsResponse response = await api.RequestCredential(...);
...
}

How to hide status query string from Url after updating from MVC Controller

I have a view which shows info according to a specific Id.
My Controller is:
public ActionResult ModifyWorkout(string WorkoutId, bool? Status)
{
Guid pkWorkoutId = new Guid(WorkoutId);
BLLWorkouts _objBLLWorkouts = new BLLWorkouts();
var WorkoutRow = _objBLLWorkouts.GetOneWorkout(pkWorkoutId);
WorkoutModel PageModel = new WorkoutModel
{
pkWorkoutId = WorkoutRow.pkWorkoutId,
WorkoutName = WorkoutRow.WorkoutName,
WorkoutNote = WorkoutRow.WorkoutNote,
Sessions = WorkoutRow.Sessions,
CmpFlag = WorkoutRow.CmpFlag,
tblWorkoutSessions = WorkoutRow.tblWorkoutSessions
};
ViewBag.UpdateStatus = Status;
return View(PageModel);
}
I always pass a Query String as Workout id for getting a single record. But when I update that records it is posting to another action:
public ActionResult UpdateWorkout(WorkoutModel model)
{
bool _status = false;
BLLWorkouts _objBLLWorkouts = new BLLWorkouts();
tblWorkout _row = new tblWorkout();
_row.WorkoutName = model.WorkoutName;
_row.WorkoutNote = model.WorkoutNote;
_row.Sessions = model.Sessions;
_row.pkWorkoutId = model.pkWorkoutId;
_row.CmpFlag = model.CmpFlag;
_status = _objBLLWorkouts.UpdateWorkout(_row);
return RedirectToAction("ModifyWorkout", new { WorkoutId = model.pkWorkoutId, Status = _status });
}
Now problem is that after updating my url becomes like this:
/ModifyWorkout?WorkoutId=438b6828-1a21-4ad0-9e40-485dda75b1f6&Status=true"
And Status message is shown even after refreshing the page due to &Status=true in Url.
<div >
#if (ViewBag.UpdateStatus != null)
{
if (ViewBag.UpdateStatus)
{
<span class="successmsgCommon">Workout updated successfully.</span>
}
else
{
<span class="errormsgCommon">Workout was not updated. Please try again.</span>
}
}
</div>
Is there any way to solve this?
Use TempData to send the value
TempData["Status"] = true;
Consume
if (TempData["Status"])
About TempData
TempData is used to pass data from current request to subsequent request means incase of redirection.
TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session
You can use TempData for this:
TempData["Status"] = _status;
return RedirectToAction("ModifyWorkout", new { WorkoutId = model.pkWorkoutId });
ASP.NET MVC will store this value for the next request so you can read it in the redirected action.
if ((bool)TempData["Status"])
{
<span class="successmsgCommon">Workout updated successfully.</span>
}
else
{
<span class="errormsgCommon">Workout was not updated. Please try again.</span>
}

View doesn't refresh after RedirectToAction is done

Here is my problem:
[HttpPost]
public ActionResult AddData(CandidateViewModel viewModel)
{
var newCandidateId = 0;
newCandidateId = this._serviceClient.AddCandidate(viewModel);
return RedirectToAction("DisplayCandidate",new {id=newCandidateId});
}
public ActionResult DisplayCandidate(int id)
{
var candidateViewModel= this._serviceClient.GetCandidate(id);
return View(candidateViewModel);
}
After filling the form viwemodel sends to server. After data were stored, flow is redirected to DisplayCandidate action and it goes there but page didn't refresh. I don't understand why! Help, please.
Because you are using Ajax Post
public ActionResult AddData(CandidateViewModel viewModel)
{
var newCandidateId = 0;
newCandidateId = this._serviceClient.AddCandidate(viewModel);
string ReturnURL = "/DisplayCandidate/"+newCandidateId;
return JSON(ReturnURL);
}
and in your Ajax Post Method:
Onsuccess(function(retURL){ window.location(retURL); })
This will take to the new Action and that Action will return View.
If you're using Ajax, return a script results to execute the navigation
instead of
return RedirectToAction("DisplayCandidate",new {id=newCandidateId});
try
var viewName = "/Path/ViewName";
var id = 1;
var urlNavigate = string.Format("location.href='{0}?id={1}'", viewName, id);
return new JavaScriptResult() { Script = urlNavigate };

How to redirect to a controller action from a JSONResult method in ASP.NET MVC?

I am fetching records for a user based on his UserId as a JsonResult...
public JsonResult GetClients(int currentPage, int pageSize)
{
if (Session["UserId"] != "")
{
var clients = clirep.FindAllClients().AsQueryable();
var count = clients.Count();
var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
var genericResult = new { Count = count, Results = results };
return Json(genericResult);
}
else
{
//return RedirectToAction("Index","Home");
}
}
How to redirect to a controller action from a JsonResult method in asp.net mvc?Any suggestion...
EDIT:
This doesn't seem to work...
if (Session["UserId"] != "")
{
var clients = clirep.FindAllClients().AsQueryable();
var count = clients.Count();
var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
var genericResult = new { Count = count, Results = results ,isRedirect=false};
return Json(genericResult);
}
else
{
return Json({redirectUrl = Url.Action("Index", "Home"), isRedirect = true });
}
This will depend on how you are invoking this controller action. As you are using JSON I suppose that you are calling it in AJAX. If this is the case you cannot redirect from the controller action. You will need to do this in the success callback of the AJAX script. One way to achieve it is the following:
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
And in the success callback:
success: function(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
Remark: Make sure to include isRedirect = false in the JSON in case you don't want to redirect which is the first case in your controller action.
Adding to Darin Dimitrov's answer. For C#.NET MVC - If you want to redirect to a different page/controller and want to send an Object/Model to the new controller, You can do something like this.
In the JsonResult Method (in the controller):
ErrorModel e = new ErrorModel();
e.ErrorTitle = "Error";
e.ErrorHeading = "Oops ! Something went wrong.";
e.ErrorMessage = "Unable to open Something";
return Json(new
{
redirectUrl = Url.Action("Index", "Home",e),
isRedirect = true
});
And in the success callback:
success: function(json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
}
And if the new controller can accept the model/object like below.. you can pass the object to the new controller/page
public ActionResult Index(ErrorModel e)
{
return View(e);
}
Hope this helps.
What to do you think about trying to call:
return (new YourOtherController()).JSONResultAction();
instead of using redirects?
And if you work with areas ...
Controller:
return Json(new
{
redirectUrl = Url.Action("Index", "/DisparadorProgSaude/", new { area = "AreaComum" }),
isRedirect = true
});
View:
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
},
No way to do this, the client is executing an AJAX script so will not be able to handle anything else.
I suggest you redirect in the client script based on the returned data in the callback function.
Take a look at a similar question here: http://bytes.com/topic/javascript/answers/533023-ajax-redirect

Resources