简体   繁体   中英

In ASP.net MVC Can I process through my cshtml logic before finishing the controller action?

I have a controller who has database logic occurring in the controller action. In addition, I know it's probably not ideal but I have some logic occurring my views. This does some sql queries and potentially those queries might update records. I have a transaction that I open at the beginning of my controller's action. In an attempt at dealing w/ this problem, I held it until after the View() call of my action with the hope that the view logic would execute before I had to commit my transaction. However, this doesn't seem to work as it only seems to process the view logic after the controller's action fully completes.

ViewBag.Message = message;
                ViewBag.Test = test;

                var result = View();

                LegacyDataManager.Commit();
                Data.Commit();

                return result;
            }
            finally
            {
                LegacyDataManager.Stop();
                Data.CloseInstance();
            }

An alternative solution is that I hold off performing the closing of my transactions until the end of the view's logic but this seems even more wrong than what I'm currently trying.

My end goal is that all necessary logic occurs before I close the transaction.

Thanks.

In ASP.net MVC Can I process through my cshtml logic before finishing the controller action?

No.

The control flow is that the controller performs its logic and then passes control to the view when it's done and ready to render the view.

It sounds like the root of the problem is that you have too much logic in your view. For example:

This does some sql queries and potentially those queries might update records.

That should definitely not happen in a view. A view just renders the result, nothing more. The only logic therein would be conditionally rendering the view differently based on the state of the model. It should not have side-effects outside of rendering the view.

The current design is fundamentally flawed, your best bet is to correct the design of your application instead of trying to coerce the framework to fit your design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM