简体   繁体   中英

ASP.Net MVC Client Side and Server Side Calculations

I am new to ASP.Net MVC and am trying to maintain the correct use of the MVC development pattern. I am getting a bit lost in the mix with all the different technologies at play.

Basically I have form that is strongly typed against a model. For simplicity sake lets say the model has three ints in it. Int1, Int2 and Total. I want to create a form that allows the user to enter values in Int1 and Int2 and then immediately update the Total field that is displayed to the user whenever either one of them changes. I then want to allow the user to hit save if they are happy with the total and HTTP Post back to the controller all three fields to be saved to a database.

Now I went down the path of using Jquery OnChange() to do the calculations and set the value of the total which works. However, I feel as though I am getting away from true MVC here as I am doing calculations within my view.

How would things like Knockout and JSON play in here? I want to stay to the best practices of MVC as much as possible.

Knockout and JSON would still be posting back to the server. Doing things client-side is encouraged, as it makes your application more responsive. You should only post to the server if you absolutely have to. I tend to make it a point to do however much I can client-side, to a certain degree.

MVC only deals with sending the requested webpage to the user's web browser. Once the browser has received it, MVC will not enter the picture again, unless you send a new web request (whether by page redirect, ajax call, or any other means to launch a web request).

Anything that happens in the browser, is not part of MVC. That doesn't mean you should steer clear from client-based interactions! It only means that you'll be using something other than MVC to provide that part of the user experience.

There are plenty of javascript frameworks to choose from if you have a sizeable need for a client-side smooth user experience.

But for the example of having a total calculated when the user enters separate values, that can easily be solved by javascript, and perhaps preferably jQuery.

But you shouldn't worry about moving away from the MVC structure. It's not supposed to be an all-encompassing framework. There's a beautiful synergy between ASP.Net MVC and javascript/jQuery, and I can only encourage such an approach.

Long story short: you're on the right track. No reason to doubt yourself.

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