简体   繁体   中英

ASP.net mvc3 Get data from View to Controller C#

I am currently using ViewBag to pass a Datatable, and some other dynamic data to the view. The data is displayed to the user in a table, and depending on which columns the user chooses, certain calculations are performed. My problem is, these calculations need to be chained, so that when the user performs a calculation, the state of the data is maintained, and further calculations on that data are then possible.

How can I get the current datatable state from the view into the controller each time? The calculations need to be performed on that current state.

If it makes any difference, I could easily change the view into a strongly typed view, and create a new object to abstract the datatable and the other dynamic data away.

Any advice welcome.

Thanks.

This sounds like some AJAX to me. You should be able to post the state back to the server (another method in your controller) and store it however you need to.

MVC3 has some great JSON stuff which should make your life easier. That + jQuery, you should be laughing.

I do encourage you to avoid DataTables and DataSets if possible. They should be considered to be the worst kind of DTO's since you can never guarantee what they contain and when (unless you follow the call chain back to their origin and make sure that they are not changed anywhere on the way).

By using proper view models you know what they contain by just looking at them, and you can also put all formatting logic inside them instead of in the view.

I've written a blog entry about why you should use view models: http://blog.gauffin.org/2011/07/three-reasons-to-why-you-should-use-view-models/

As for your question: The easiest way is to use jQuery/Ajax and return Json (which is easy if you are using proper view models).

<script type="text/javascript">
 $(function() { //<-- runs the script when the document has been loaded

    $('#formid').submit(function() { // <--- hook form submit event

        $.post('@Html.Action("CalcOne")?option='+ $('#id').val(), function(data) {
            var result = data.result;
            $.post('@Html.Action("CalcTwo")?option='+ result, function(data) {
                    //do third calc
            });
        });
    });
 });
</script>

And in your controller:

[HttpPost]
public ActionResult CalcOne(int option)
{
    //do some calculations
    return Json(new MyModel{ Result = option + 1 });
}

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