【问题标题】:How can I preserve the form values when I use MVC with Knockout将 MVC 与 Knockout 一起使用时如何保留表单值
【发布时间】:2013-12-17 16:35:04
【问题描述】:

我正在开发(第一次)使用 ajax 调用和淘汰 MVVM 来填充 2 个级联下拉列表的 MVC 应用程序。 问题是,当我发布网页时,如何保留我在下拉列表中选择的值? 我正在开发的网页在发布到控制器时进行计算,控制器必须返回计算结果。返回结果时,必须保留表单的值。

视图的一部分

    @using (Html.BeginForm("Calculate", "Entypo", FormMethod.Post, new { role = "form" }))
{
     @Html.AntiForgeryToken()
    @Html.ValidationSummary(false)

    <fieldset>
        <legend>Printers</legend>
        <div class="row">
            <div class="form-group col-md-6">
                <select id="printers" name="printers" class="form-control" data-bind="options: printers, optionsValue: 'ID', optionsText: 'BrandModelName', value: selectedPrinter, optionsCaption: 'Choose Printer...'"></select>
             </div>
            <div class="form-group col-md-6">
                <select id="sheets" name="sheets" class="form-control" data-bind="options: sheets, optionsValue: 'ID', optionsText: 'Description', optionsCaption: 'Choose Sheet...', enable: sheets().length, value: sheet">
                </select>
            </div>
        </div>
    </fieldset>
    <div class="row">
            <div class="col-md-12" style="padding-bottom:10px;">
                <input type="submit" value="Calculate" class="btn btn-primary" />
            </div>
        </div>
    }
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/knockout-3.0.0.js"></script>
    <script>
        $(document).ready(function () {
            // MVVM
            viewModel = {
                printer: ko.observable(),
                printers: ko.observableArray(),
                sheet: ko.observable(),
                sheets:ko.observableArray(),
                paper: ko.observable(),
                papers: ko.observableArray(),
                weight: ko.observable(),
                weights: ko.observableArray(),
                size: ko.observable(),
                sizes: ko.observableArray(),
                lamA: ko.observableArray(),
                lamAvalue: ko.observable(),
                lamB: ko.observableArray(),
                lamBvalue: ko.observable(),
                chkCut: ko.observable(false),
                chkFold: ko.observable(false),
                chkPick: ko.observable(false),
                chkPerfore: ko.observable(false),
                standardSize: ko.observable(),
                x: ko.observable(),
                y: ko.observable(),
                bleed: ko.observable(2.5),
                qty: ko.observable(1)
            };

            viewModel.standardSize.subscribe(function () {
                var st = viewModel.standardSize();

                var res = st.split("x");
                viewModel.x(res[0]);
                viewModel.y(res[1]);
            });

            $.ajax({
                url: '/Entypo/getPrinters',
                type: 'GET',
                dataType: 'json',
                data: {},
                success: function (data) {
                    viewModel.printers(data);
                }
            });

            viewModel.selectedPrinter = ko.dependentObservable({
                read: viewModel.printer,
                write: function (printer) {
                    this.printer(printer);
                    $.ajax({
                        url: '/Entypo/getSheets',
                        type: 'GET',
                        dataType: 'json',
                        data: { id: viewModel.selectedPrinter() },
                        success: function (data) {
                            viewModel.sheets(data);
                        }
                    });
                },
                owner: viewModel
            });

            $.ajax({
                url: '/PaperSize/getPapers',
                type: 'GET',
                dataType: 'json',
                data: {},
                success: function (data) {
                    viewModel.papers(data);
                }
            });

            viewModel.selectedPaper = ko.dependentObservable({
                read: viewModel.paper,
                write: function (paper) {
                    this.paper(paper);
                    $.ajax({
                        url: '/Entypo/getWeights',
                        type: 'GET',
                        dataType: 'json',
                        data: { id: viewModel.selectedPaper() },
                        success: function (data) {
                            viewModel.weights(data);
                        }
                    });
                },
                owner: viewModel
            });

            viewModel.selectedWeight = ko.dependentObservable({
                read: viewModel.weight,
                write: function (weight) {
                    this.weight(weight);
                    $.ajax({
                        url: '/Entypo/getSizes',
                        type: 'GET',
                        dataType: 'json',
                        data: { id: viewModel.selectedWeight() },
                        success: function (data) {
                            viewModel.sizes(data);
                        }
                    });
                },
                owner: viewModel
            });

            $.ajax({
                url: '/Entypo/getLamination',
                type: 'GET',
                dataType: 'json',
                data: {},
                success: function (data) {
                    viewModel.lamA(data);
                    viewModel.lamB(data);
                }
            });

            ko.applyBindings(viewModel);
        });


    </script>

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QVNet_v2.Models;

namespace QVNet_v2.Controllers
{
    public class EntypoController : Controller
    {
        private QVNetEntities db = new QVNetEntities();

        //
        // Calc: /Entypo/
        [HttpGet]
        public ActionResult Calculate()
        {

            return View();
        }

        [HttpPost]
        public ActionResult Calculate()
        {
            return View();
        }


        //GET PRINTERS
        public JsonResult getPrinters()
        {
            var printers = db.Printers.Select(s => new { s.ID, s.BrandModelName }).OrderBy(s=>s.BrandModelName).ToList();
            return Json(printers, JsonRequestBehavior.AllowGet);
        }
        //GET SHEETS USED FROM SELECTED PRINTER
        public JsonResult getSheets(int id)
        {
            var sheets = db.Sheets.Select(s => new { s.ID, s.Description, s.PrinterID }).Where(s=>s.PrinterID ==id).OrderBy(s=>s.Description).ToList();
            return Json(sheets, JsonRequestBehavior.AllowGet);
        }
        // GET PAPERS
        public JsonResult getPapers()
        {
            var papers = db.Papers.Select(s => new { s.ID, s.Description }).OrderBy(s => s.Description).ToList();
            return Json(papers, JsonRequestBehavior.AllowGet);
        }
        // GET WEIGHTS OF SELECTED PAPER
        public JsonResult getWeights(int id)
        {
            var weights = db.PaperWeights.Select(s => new { s.ID, s.Weight, s.PaperID }).Where(s => s.PaperID == id).OrderBy(s => s.Weight).ToList();
            return Json(weights, JsonRequestBehavior.AllowGet);
        }
        //GET SIZES OF SELECTED PAPER AND WEIGHT
        public JsonResult getSizes(int id)
        {
            var sizes = db.PaperSizes.Select(s => new { s.ID, s.Description, s.PaperWeightID }).Where(s => s.PaperWeightID == id).OrderBy(s => s.Description).ToList();
            return Json(sizes, JsonRequestBehavior.AllowGet);
        }
        //GET LAMINATION
        public JsonResult getLamination()
        {
            var lam = db.SheetLaminations.Select(s => new { s.ID, s.Description }).OrderBy(s => s.Description).ToList();
            return Json(lam, JsonRequestBehavior.AllowGet);
        }
        //Dispose db
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

当用户点击提交值时,控制器必须从表单中获取数据并返回计算结果,同时保持表单字段的完整性。

对不起我的英语。

【问题讨论】:

  • 你能发布一些你的代码吗
  • 非常糟糕的问题并且没有代码。定义保留。就像在刷新页面时保留而不询问服务器它们的值是什么?

标签: asp.net-mvc knockout.js


【解决方案1】:

你有两种可能的方法。

  1. 使用 ajax 提交表单。您将保留您的表格 open 因此所有值都将保持不变。您可以使用@using (Ajax.BeginForm) 或创建将调用$.ajax 的剔除方法来保存您的数据并 分配这个方法来提交按钮。

  2. 第二种方法 - 使您的表单强类型。创建视图模型 将保存构造表单所需的所有值的类。在 您的保存操作(Calculate 方法用 [HttpPost] 注释) 您应该根据实际表单值重新创建视图模型并将其发送 回到视图。

【讨论】:

  • 感谢您的帮助。我按照你的建议做了。但现在我面临插入小数的问题。不显眼的验证否认两者。而且,
  • 至于我 - 我已经为小数创建了自定义绑定类来接受两者。并且,这是该方法的好链接:stackoverflow.com/questions/793459/…
  • @PavelKutakov,我有一个问题。如果表单不是强类型,ajax.beginform 是否仍然保留这些值?意味着如果我使用像 这样的纯 html,那么值会被保留吗?
  • 如果是,如何实现?
  • 如果您的表单不是强类型的,您必须将默认值放入来自 viewmodel 数据或 ViewBag 变量的输入中。
猜你喜欢
  • 1970-01-01
  • 2016-02-15
  • 2012-12-15
  • 2017-02-20
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
相关资源
最近更新 更多