Use of await in Razor views

mvc call async method from view
mvc async method in controller
why use async/await in web api
async and await in c# corner
async/await c#
mvc controller async vs sync
razor shared view
difference between synchronous and asynchronous in mvc

Is it possible to await on tasks in Razor .cshtml views?

By default it complains that it can only be used in methods marked with async so I'm wondering if maybe there is a hidden switch somewhere that enables it?

In ASP.NET Core 2.1, you can use await in Razor views.



@await Html.PartialAsync("../Account/_LoginPartial.cshtml")

Using Asynchronous Methods in ASP.NET MVC 4, In this article, I will create a simple MVC application to elaborate the answers to all the above questions. Async. Async keyword is used to call the  Is it possible to await on tasks in Razor .cshtml views? By default it complains that it can only be used in methods marked with async so I'm wondering if maybe there is a hidden switch somewhere

No, that's not possible and you shouldn't need to do it anyway. Razor views should contain markup and at most some helper call. async/await belongs to your backend logic.

razor syntax reference for ASP.NET Core, cshtml files in the same Blazor project. Is this a limitation of Razor components? (​Why?) It isn't mentioned in the component docs or the general  Razor syntax. Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output. When an @ symbol is followed by a Razor reserved keyword, it transitions into Razor-specific markup. Otherwise, it transitions into plain C#. To escape an @ symbol in Razor markup, use a second @ symbol:

I've wanted something like this for a long time - a lot of the pages we write could be thrown together by a Jr Dev if they didn't have to write a bunch of queries; and, it's the same basic query boilerplate every time anyway - why should they have to write them for each Controller, when the majority of their work is to get content up? I use C# so I don't have to deal with memory management, why should an HTML coder have to deal with query details?

There is a trick you can use to sort of implicitly load data async into the View. First, you define a class that expresses what data you want. Then, at the top of each View, instantiate that class. Back in the Controller, you can lookup the View you know you're going to use, open it, then compile that class. You can then use it to go get the data the View will need, async, in the Controller the way MVC enforces. Finally, pass it off with a ViewModel to the View as MVC prescribes, and, through some trickery - you have a View that declares what data it's going to use.

Here's a StoryController. Jr Devs write stories as simple .cshtml files without having to know what a Controller, database or LINQ is:

public class StoryController : BaseController
    // /story/(id)
    public async Task<ActionResult> Id(string id = null)
        string storyFilename = id;

        // Get the View - story file
        if (storyFilename == null || storyFilename.Contains('.'))
            return Redirect("/");   // Disallow ../ for example

        string path = App.O.AppRoot + App.HomeViews + @"story\" + storyFilename + ".cshtml";
        if (!System.IO.File.Exists(path))
            return Redirect("/");

        return View(storyFilename);

All this does for now is go get the View file based on the URL, allowing something like WebForms (except inside MVC and using Razor). But we want to show some data - in our case, people and projects that accumulate in the database - with some standard ViewModels and Partials. Let's define how and compile that out. (Note that ConservX happens to be the core Project namespace in my case.)

    public async Task<ActionResult> Id(string id = null)
        string storyFilename = id;

        // 1) Get the View - story file
        if (storyFilename == null || storyFilename.Contains('.'))
            return Redirect("/");   // Disallow ../ for example

        string path = App.O.AppRoot + App.HomeViews + @"story\" + storyFilename + ".cshtml";
        if (!System.IO.File.Exists(path))
            return Redirect("/");

        // 2) It exists - begin parsing it for StoryDataIds
        var lines = await FileHelper.ReadLinesUntilAsync(path, line => line.Contains("@section"));

        // 3) Is there a line that says "new StoryDataIds"?
        int i = 0;
        int l = lines.Count;
        for (; i < l && !lines[i].Contains("var dataIds = new StoryDataIds"); i++)

        if (i == l) // No StoryDataIds defined, just pass an empty StoryViewModel
            return View(storyFilename, new StoryViewModel());

        string className = "__StoryData_" + storyFilename;
        string code = String.Join(" ",
            (new[] {
                "using ConservX.Areas.Home.ViewModels.Storying;",
                "public class " + className + " { public static StoryDataIds Get() {"
                lines.Skip(i).TakeWhile(line => !line.Contains("};"))
                new[] { "}; return dataIds; } }" }

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;
        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

        using (var db... // Fetch the relevant data here

        var vm = new StoryViewModel();
        return View(storyFilename, vm);

That's the majority of the work. Now Jr Devs can just declare the data they need like so:

@using ConservX.Areas.Home.ViewModels.Storying
@model StoryViewModel
    var dataIds = new StoryDataIds
        ProjectIds = new[] { 4 }

    string title = "Story Title";
    ViewBag.Title = title;
    Layout = "~/Areas/Home/Views/Shared/_Main.cshtml";
@section css {

Use Asynchronous Methods in MVC 4 with Examples, NET MVC (including the ContentManagement class and A snippet of the IndexAsync action's view, showing that the method took 5007 milliseconds to By designing this to use async , we cut our total execution time in half! Use of await in Razor views (8 answers) Closed 4 years ago . My model has an async method which I would like to invoke from within a view, i.e. something like this:

I landed on this question because I am a newbie to Razor and I wanted to display a simple "loading..." screen while my Controller Code was calculating data.

So I found this link: which was helpful, but because I was a total novice at Razor, I was unable to make this work.

What finally worked for me was the following.

1) Add the "loading" div as suggested in the code project to my .cshtml file:

<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px;
    top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001;
    opacity: .8; filter: alpha(opacity=70);display:none">
    <p style="position: absolute; top: 30%; left: 45%; color: White;">
        Loading, please wait...<img src="../../Content/Images/ajax-loading.gif">

2) Modify my Razor form from

<input type="submit" value="Go"/>


<input type="button" value="Go" onclick="JavascriptFunction()" />

3) Create the JavascriptFunction() in my .cshtml page:

<script type="text/javascript" language="javascript">
    function JavascriptFunction() {

If I understand all of the above correctly, what this does is execute the function JavascriptFunction when I press the Go button.

The JavascriptFunction does 2 things: 1) Change the view of the page by showing the previously hidden (display:none) divLoading div. 2) Submit all the forms on this page (I only have one, so it submits the form the same as if I had they type submit on the button)

After the Controller launched by the form submit is done, it loads a new view on a new page, and the initial page (and the "loading" div) is gone. Mission accomplished.

Async, Await And Asynchronous Programming In MVC, Async task in MVC Example, async await example c#, Await And that will allow multiple things to occur in application at the same time without blocking async service method in your razor view, for example i want to display student​  Use a partial view in a Razor Pages PageModel. In ASP.NET Core 2.0 or 2.1, the following handler method renders the _AuthorPartialRP.cshtml partial view to the response: C#. public IActionResult OnGetPartial() => new PartialViewResult { ViewName = "_AuthorPartialRP", ViewData = ViewData, };

You can await calls in razor pages? I have a Blazor app and most of my methods are async:

Razor page:

<MatFAB Icon="@MatIconNames.Autorenew" Style="transform:scale(0.8); background:#333;"
                OnClick="@(async () => await OnInitializedAsync())"></MatFAB>

This is a MatBlazor FloatingActionButton which calls the life time cycle event OnInitializedAsync()

C# Code:

protected override async Task OnInitializedAsync()
    // Do something like get data when the form loads

Razor components: error using await in Razor expressions (Preview , Examples of use cases for view components include data-driven menus, tag View components consist of a class file and a .cshtml view file. endPoint = "​";; var json = await client. Every time I try to use the new Async and Await operators and return a collection of objects from a database I get an Invalid Operation exception. When I use it to only return a single Item it works fine.

Explaining Async and Await in ASP.NET, 1) It can make application to handle more users. 2) It can We can implement asynchronous actions using “async / await” return View(data);. A Razor Page is very similar to the view component that ASP.NET MVC developers are used to. It has all the same syntax and functionality. It has all the same syntax and functionality. The key difference is that the model and controller code is also included within the Razor Page itself.

Async task in MVC Async await example c#, Use Asynchronous Methods in MVC 4 with Examples In today world most of application work based on Synchronous programming in which client sent request to server and server process the task and send response back to client.

View Components in Razor Pages, In most cases, this will be done in a Razor View; less frequently, from a Controller action. Either method accepts the name of the View Component and an optional anonymous object containing parameters. Invoking a View Component from a Razor View. For invocation via Razor, the syntax is simply: @await Component.

  • Seems like something you would do in your controller or further up the stack in your back end code.
  • Downvote for the "Don't do this" part. Rendering first bytes before data arrives isn't strange, nor are View-dictated data needs. For example, if I handed an intern Razor and they needed to throw pages together without knowing how to call the DB, I could teach them to call for data via a lazy-loading repo with a really simple interface - except you run into this wall of async (possibly) being restricted in Razor.
  • @ChrisMoschini that just doesn't make any sense at all. "view-dictated data need" is what a ViewModel is and it's already provided by the controller. "rendering before data arrives" is just a looking at the slow data retrieval problem the wrong way. there is caching for that.
  • @ssg Consider a page that's different for everyone, every time they visit, and it takes some time to calculate the results. Suppose it's a list of stuff. Better to render, unbuffered, to the outputstream what you have as soon as you have it, than to make the user wait until absolutely everything has arrived. The ViewModel approach would get you the crappy latter outcome. Letting the View sip and render data in real-time gives you the better, low-time-to-first-result former outcome.
  • @ChrisMoschini you confuse browser-side processing with server-side processing. A View is supposed to work on the finished data after all asynchronous operations have finished in the controller. It's the controller's job to get the data, not the view's. If you want partial rendering, structure your HTML and Javascript so that rendering starts before all data was downloaded. If you want the two things separate, use ODATA or Web API to get the Json. What you are describing is more-or-less the way Web Forms worked.
  • @PanagiotisKanavos Incorrect. When a Response begins, it doesn't instantly transfer all its contents to the client. Instead, it streams over time. You can render gradually from the server as the data becomes available if you deliver your View in an unbuffered way - but the standard approach to ASP.Net MVC/Razor makes this either difficult or impossible. Going and fetching more data via js after the fact is something entirely different, and not to be confused with streaming a single response over the course of several seconds, without the need for additional requests.
  • This is equivalent to var foo = await... bar = await ... return View("Index", new { foo=foo, bar=bar }) - you're still just loading data via await/async in the Controller as normal, not in Razor.
  • The correct answer is "You are doing it wrong". This should be done in an asynchronous way in the controller's method. Trying to talk from the view directly to a database,bypassing both the controller, model and any data layer is the exact opposite of MVC and simply causes delays in rendering. The view should just render the data in a view model. The view model should only contain the data needed for that view. It's the controller's job to retrieve the data and constuct the DTO/model and send it to the view
  • @PanagiotisKanavos Wouldn't that mean that for a large listing retrieved one-by-one piece from database the rendering and actually sending the output to the client would not occur until the full list is loaded to memory? It definitely makes sense to have logic in controller, however for the case I mentioned, wouldn't it be better to be able to pass some sort of async enumerable, and render it piece-by-piece asynchronously in view? Or is there some technical limitation for that?
  • @martinh_kentico no, not at all. If you are loading entries one by one there is a serious problem in the data access logic. Why load one by one when a query will return all results at once? Why return a lot of results when you can't display them? Why not use paging in this case? Why not use a .Contains() clause in LINQ, or IN (..) in SQL to pass a list of IDs?
  • @martinh_kentico even worse - what would be the point ot an async operation in the view? You can't send the HTML response to the browser until all of this finishes anyway. If you want to fill parts of a page when data becomes available you have to use AJAX on the browser, or really old-style frames.
  • You don't query the data one by one, you get DataReader for the query and stream the data directly from DB if you work with larger amount of data. Also, the output is s stream, so why would you need to wait for the whole page to be rendered before starting to send the data to client? If WebForms is capable of streaming output as it renders, why MVC couldn't? Also, if you work with component-based models, having more components which call external services would mean that you need to initiate those external calls sequentially.
  • This is fire and forget - doesn't work if you need to return value from that function.