public async Task<ActionResult> Print(BasicSurveyReportViewModel paramModel)
{
ActionResult OverallSummary =
await basicSurveyReportController.OverallSummary(paramModel);
ActionResult CompanyInfo =
await basicSurveyReportController.CompanyInfo(paramModel);
ViewBag.OverallSummary = OverallSummary;
ViewBag.CompanyInfo = CompanyInfo;
return View();
}
In this code, first OverallSummary variable is set successfully.
But when running at the CompanyInfo line's method, it puts the variable into both CompanyInfo and OverallSummary.
How do I can get the results into separate variables?
It looks like you're trying to call asynchronous child actions, which are not supported in ASP.NET 4.x. I suspect that the ASP.NET controller is just accessing the current request when you return View(blah) or whatever from your child actions.
The only way to correctly do this (in the current version of ASP.NET) is to write helper methods that do the actual work and return your own types (not ActionResult):
OverallSummary GetOverallSummaryAsync(BasicSurveyReportViewModel model);
CompanyInfo GetCompanyInfoAsync(BasicSurveyReportViewModel model);
public async Task<ActionResult> Print(BasicSurveyReportViewModel paramModel)
{
OverallSummary overallSummary =
await GetOverallSummaryAsync(paramModel);
CompanyInfo companyInfo =
await GetCompanyInfoAsync(paramModel);
ViewBag.OverallSummary = overallSummary;
ViewBag.CompanyInfo = companyInfo;
return View();
}
Then your other controller actions can convert to use those methods as well, like this:
public async Task<ActionResult> OverallSummary(BasicSurveyReportViewModel paramModel)
{
return View(await GetOverallSummaryAsync(paramModel));
}
Related
I have three actions that I have a value in the first action, I pass this value to the second action. I want to use this amount in the third action, is there a solution?
First Action:
public async Task<IActionResult> LoginUser(LoginViewModel viewModel)
{
string code = await _user.SendActiveCodeForUser(viewModel);
TempData["Mobile"] = viewModel.Mobile;
return Json(new { redirectToUrl = Url.Action("Activate") });
}
Second Action:
public IActionResult Activate()
{
ViewBag.Mobile = TempData["Mobile"].ToString();
return View();
}
Third Action:
public async Task<IActionResult> SendActiveCode()
{
string code = await _user.SendActiveCodeAgain(ViewData["Mobile"].ToString());
return Json(0);
}
I used the session according to the link address below, I think it is a good solution
How To Use Sessions In ASP.NET Core
I'm pretty new with ASP.Net Core and I'm trying to show my async Task Filter return into my View but not sure how to...
This is my Controller code:
public class OrderNumberController : Controller
{
public async Task<IActionResult> Index(string orderNumber)
{
string[] locales = HPMSConstants.System.SupportedLocales.OrderBy(l => l).ToArray();
ViewBag.Locales = locales;
return View();
}
[HttpPost]
public async Task<PaymentGatewayTransactionManagerService.PaymentGatewayRecord> Filter(string orderNumber)
{
var result = await GetOrders(orderNumber);
return result;
}
private async Task<PaymentGatewayTransactionManagerService.PaymentGatewayRecord> GetOrders(string orderNumber)
{
var httpBinding = new System.ServiceModel.BasicHttpBinding();
// var address = new System.ServiceModel.EndpointAddress("http://pgtms.local.myherbalife.com/PaymentGatewayTransactionManager/Service.svc");
//var address = new System.ServiceModel.EndpointAddress("http://zus2q1ssb000000.hrbl.net:8330/Service.svc");
var address = new System.ServiceModel.EndpointAddress("http://zuswqa4svc01:8330/Service.svc");
PaymentGatewayTransactionManagerClient clientService = new PaymentGatewayTransactionManagerClient(httpBinding, address);
var result = await clientService.GetPaymentGatewayRecordAsync(orderNumber);
return result;
}
I think I see what you are asking. In the second two methods you are returning a Task<something> where the "something" is the result that you got after awaiting the result from an async method call. The first method is showing an MVC view controller method returning a view. It turns out that method is coded wrong. It should be (ignoring the first two lines which seem unrelated to the problem)
public IActionResult Index(string orderNumber)
{
string[] locales = HPMSConstants.System.SupportedLocales.OrderBy(l => l).ToArray();
ViewBag.Locales = locales;
return View();
}
This you don't need the async Task<IActionResult> because you are not awaiting any asynchronous methods within the method shown. View() is a method on the Microsoft.AspNetCore.Mvc.Controller which is not asynchronous and returns a Microsoft.AspNetCore.Mvc.ViewResult, which extends a ActionResult.
So the short answer is, just make sure your method returns the values it says it does in the method signature and make sure not to ignore the warnings and errors in Visual Studio or Visual Code. There is a warning if you add async to a method but you do not await anything in the body. There is an error if you try to return a Task<IActionResult> but are returing something that implements IActionResult instead.
I have created an API using ASP.NET MVC Core v2.1. One of my HttpGet methods is set up as follows:
public async Task<IActionResult> GetConfiguration([FromRoute] int? id)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
..... // Some code here
return Ok(configuration);
}
catch (Exception ex)
{
... // Some code here
}
}
When unit testing this I can check that Ok was the response, but I really need to see the values of the configuration. I don't seem to be able to get this to work with the following:
[TestMethod]
public void ConfigurationSearchGetTest()
{
var context = GetContextWithData();
var controller = new ConfigurationSearchController(context);
var items = context.Configurations.Count();
var actionResult = controller.GetConfiguration(12);
Assert.IsTrue(true);
context.Dispose();
}
At runtime, I can check that actionResult has certain values that I am unable to code for. Is there something I am doing wrong? Or am I just thinking about this wrong? I would like to be able to do:
Assert.AreEqual(12, actionResult.Values.ConfigurationId);
You can get tested controller without changing returned type.
IActionResult is base type for all others.
Cast result into expected type and compare returned value with expected.
Since you are testing asynchronous method, make test method asynchronous as well.
[TestMethod]
public async Task ConfigurationSearchGetTest()
{
using (var context = GetContextWithData())
{
var controller = new ConfigurationSearchController(context);
var items = context.Configurations.Count();
var actionResult = await controller.GetConfiguration(12);
var okResult = actionResult as OkObjectResult;
var actualConfiguration = okResult.Value as Configuration;
// Now you can compare with expected values
actualConfuguration.Should().BeEquivalentTo(expected);
}
}
Good practice would suggest that you don't have a lot of code in your controller actions to test and the bulk of logic is in decoupled objects elsewhere that are much easier to test. Having said that, if you still want to test your controllers then you need to make your test async and await the calls.
One of the problems you will have is that you are using IActionResult as it allows you to return BadRequest(...) and Ok(...). However, since you are using ASP.NET MVC Core 2.1, you may want to start using the new ActionResult<T> type instead. This should help with your testing because you can now get direct access to the strongly typed return value. For example:
//Assuming your return type is `Configuration`
public async Task<ActionResult<Configuration>> GetConfiguration([FromRoute] int? id)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
..... // Some code here
// Note we are now returning the object directly, there is an implicit conversion
// done for you
return configuration;
}
catch (Exception ex)
{
... // Some code here
}
}
Note we are now returning the object directly as there is an implicit conversion from Foo to ActionResult<Foo>
Now your test can look like this:
[TestMethod]
public async Task ConfigurationSearchGetTest()
{
var context = GetContextWithData();
var controller = new ConfigurationSearchController(context);
var items = context.Configurations.Count();
// We now await the call
var actionResult = await controller.GetConfiguration(12);
// And the value we want is now a property of the return
var configuration = actionResult.Value;
Assert.IsTrue(true);
context.Dispose();
}
As my reputation does not allow me to comment on #DavidG answer which goes in the right direction, I will put a sample on how to get the value inside Task<IActionResult>.
As # Christopher J. Reynolds pointed out, actionResult.Value can be seen at runtime but not at compilation.
So, I'll show a basic test in which get the Values:
[TestMethod]
public async Task Get_ReturnsAnArea()
{
// Arrange
string areaId = "SomeArea";
Area expectedArea = new Area() { ObjectId = areaId, AreaNameEn = "TestArea" };
var restClient = new Mock<IRestClient>();
restClient.Setup(client => client.GetAsync<Area>(It.IsAny<string>(), false)).ReturnsAsync(expectedArea);
var controller = new AreasController(restClient.Object);
//// Act
// We now await the call
IActionResult actionResult = await controller.Get(areaId);
// We cast it to the expected response type
OkObjectResult okResult = actionResult as OkObjectResult;
// Assert
Assert.IsNotNull(okResult);
Assert.AreEqual(200, okResult.StatusCode);
Assert.AreEqual(expectedArea, okResult.Value);
// We cast Value to the expected type
Area actualArea = okResult.Value as Area;
Assert.IsTrue(expectedArea.AreaNameEn.Equals(actualArea.AreaNameEn));
}
For sure this could be improved but I just wanted to show you a simple way to get it.
I hope it helps.
You need to await the call to GetConfiguration to get the IActionResult object back as follows:
var actionResult = await controller.GetConfiguration(12);
To do this you need to change the signature of your test method to be async as well. So change this:
public void ConfigurationSearchGetTest()
To this:
public async Task ConfigurationSearchGetTest()
If you need fast solution,
use JsonConvert.SerializeObject() and after that JsonConvert.DeserializeObject() then you will get Object with values.
[TestMethod]
public async Task ConfigurationSearchGetTest()
{
using (var context = GetContextWithData())
{
var controller = new ConfigurationSearchController(context);
var items = context.Configurations.Count();
var actionResult = await controller.GetConfiguration(12);
var okResult = actionResult as OkObjectResult;
var actualConfiguration = okResult.Value ;
//
//IMPORTANT ONLY BELOW two lines need.
//
var actualConfigurationJStr=JsonConvert.SerializeObject( okResult.Value );
var hereObjectWithStrongType=JsonConvert.DeserializeObject<Configuration>(actualConfigurationJStr);
// Now you can compare with expected values
actualConfuguration.Should().BeEquivalentTo(expected);
}
}
Environment:
I am working in WebAPI. I implemented all CRUD methods.
Scenario:
In PUT method, i am excluding some properties like 'CreatedDate' to be updated. My Code like below;
[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
//Parsing to Business Entity
var item = TheFactory.Parse(myModel);
bool result = await _myBL.UpdateLab(item);
if (!result)
{
return BadRequest("Error in Save");
}
//Converting to view model and return
return Ok(TheFactory.Create(item));
}
Problem:
Here i am not getting CreatedDate from user. So it always min date.In DAL i specified this field as not modified so it always have the created data value. In return i am converting to viewmodel from the model user given. So CreatedDate is min date not original.
MySolution:
So to avoid that get the updated object from the Database again and return to the user. I already have get method to return the object by passing id. So i just changed my PUT method like below;
[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
//Parsing to Business Entity
var item = TheFactory.Parse(myModel);
bool result = await _myBL.UpdateLab(item);
if (!result)
{
return BadRequest("Error in Save");
}
//Redirect to getbyid method
return RedirectToRoute("GetById", new { id = item.Id });
}
Issue:
Here i thought i can reuse the method get method so it also returns ok(object). But after changed to this I got the following exception;
The requested resource does not support http method 'PUT'.
The response status is 405. Please help me to find the routecause
You need to just call GetById(item.id)
[Route("")]
public async Task<IHttpActionResult> Put(MyModel myModel)
{
//Parsing to Business Entity
var item = TheFactory.Parse(myModel);
bool result = await _myBL.UpdateLab(item);
if (!result)
{
return BadRequest("Error in Save");
}
return GetById(item.Id);
}
I have an Asynchronous controller implementation as follows,
public Task<ActionResult> UpdateUser(ProfileModel model)
{
return Task.Factory.StartNew(showMethod).ContinueWith(
t =>
{
return RedirectToAction("ViewUser","UserProfile");
});
}
However I am unable to redirect to the action as I am keep on getting the error,
Cannot implicitly convert type, System.Threading.Taska.Task<Sytem.Web.Mvc.RedirectToRouteResult> to System.Threading.Taska.Task<Sytem.Web.Mvc.ActionResult>
However I really want to redirect to the mentioned Action, how can I do that.
For people who come here looking for an answer, the newer versions of .NET make things simpler. Use the keyword async in the definition of the method and you can clear up the body.
public async Task<ActionResult> UpdateUser(ProfileModel model)
{
return RedirectToAction("ViewUser","UserProfile");
}
You need to change the return type of UpdateUser action from Task<ActionResult> to Task<RedirectToRouteResult>
public Task<RedirectToRouteResult> UpdateUser(ProfileModel model)
{
return Task.Factory.StartNew(showMethod).ContinueWith(
t => {
return RedirectToAction("ViewUser","UserProfile");
});
}
Or you could explicitly set the generic type argument of ContinueWith method with ActionResult, like this:
public Task<ActionResult> UpdateUser(ProfileModel model)
{
return Task.Factory.StartNew(showMethod).ContinueWith<ActionResult>(
t => {
return RedirectToAction("ViewUser","UserProfile");
});
}
Use this example:
public async Task<ActionResult> Login(LoginModel model) {
//You would do some async work here like I was doing.
return RedirectToAction("Action","Controller");//The action must be async as well
}
public async Task<ActionResult> Action() {//This must be an async task
return View();
}