0

我有一个集成 Bootstrap 和 Knockout 的工作应用程序。这个应用程序从我的控制器中提取数据并按照我的预期将其显示在 UI 中。当我单击或更改值时,我可以看到值已更新,但我似乎看不到将数据传回我的控制器以进行保存。我只需要知道如何解决我必须允许我将 selectedRequestorName 传递回控制器的问题。

这是一个示例类

public class Requestor
{
    public int Id { get; set; }
    public string Name { get; set; }
}

界面

interface IRequestorRepository
{
    IList<Requestor> GetAllRequestors();
}

这是带有种子数据的存储库

public class RequestorRepository : IRequestorRepository
{
    private List<Requestor> requestors = new List<Requestor>();
    private int _nextId = 1;

    public RequestorRepository()
    {
        Add(new Requestor{ Id = 1, Name = "Brian" });
        Add(new Requestor { Id = 2, Name = "Steve" });
        Add(new Requestor { Id = 3, Name = "Jake" });
    }

    public IList<Requestor> GetAllRequestors()
    {
        return requestors;
    }

    public Requestor Add(Requestor item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("Null Requestor");
        }

        item.Id = _nextId++;
        requestors.Add(item);

        return item;
    }
}

我的 HomeController 如下所示

public class HomeController : Controller
{
    static readonly IRequestorRepository req_repository = new RequestorRepository();

    // GET: /Home/
    public ActionResult Index()
    {
        ViewBag.DateNow = DateTime.Now.ToShortDateString();

        return View();
    }

    public JsonResult GetRequestors()
    {
        return Json(req_repository.GetAllRequestors(), JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public JsonResult SaveDetails(Requestor selectedRequestorName)
    {
        int id = -1;

        return Json(id, "json");
    }
}

在我的 Index.cshtml 中,页面顶部的脚本标记中有以下内容

// Global variable
var viewModel = null;

$(document).ready(function () {
    function ViewModel() {

        //Make the self as 'this' reference
        var self = this;

        // Requestors
        self.RequestorId = ko.observable("");
        self.RequestorName = ko.observable("");
        self.RequestorSourceDatabase = ko.observable("");

        var RequestorNames = {
            Id: self.RequestorId,
            Name: self.RequestorName,
            SourceDatabase: self.RequestorSourceDatabase
        };

        self.selectedRequestorName = ko.observable();
        self.RequestorNames = ko.observableArray();   // Contains the list of RequestorNames

        // Initialize the view-model for Requestors
        $.ajax({
            url: '@Url.Action("GetRequestors", "Home")',
            cache: false,
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            data: {},
            success: function (data) {
                self.RequestorNames(data);
            }
        });
        // END Requestors

        // Reset
        self.reset = function () {
            self.Name("");
        }

        // Cancel
        self.cancel = function () {
            self.Name(null);
        }
    }

    viewModel = new ViewModel();
    ko.applyBindings(viewModel);        
});

$(function () {
        $('#Save').click(function (e) {

            // Check whether the form is valid. Note: Remove this check, if you are not using HTML5
            if (document.forms[0].checkValidity()) {

                e.preventDefault();

                $.ajax({
                    type: "POST",
                    url: '@Url.Action("SaveDetails", "Home")',
                    data: ko.toJSON(viewModel.selectedRequestorName),
                    contentType: 'application/json; charset=utf-8',
                    async: true,
                    beforeSend: function () {
                        // Display loading image
                    },
                    success: function (result) {
                        if (result > 0) {
                            alert("This work request has been successfully saved in database. The Document ID is: " + result);
                        } else {
                            alert("The Work Request was not saved, there was an issue.");
                        }
                    },
                    complete: function () {
                        // Hide loading image.
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        // Handle error.
                    }
                });

            }
            else {
                alert("Form is not valid");
            }
        });
});

最后是包含显示数据的控件供用户选择...

<p>Current selection is <span data-bind="text:selectedRequestorName"></span></p>
<!-- Requestors -->
<div class="input-group col-sm-8">
  <input type="text" data-bind="value:selectedRequestorName" class="form-control item" placeholder="Requestor Name" name="Requestor">
    <div class="input-group-btn">
      <button type="button" class="btn btn-default dropdown-toggle item" data-toggle="dropdown">Select <span class="caret"></span></button>
        <ul class="dropdown-menu" data-bind="foreach: RequestorNames">
          <li class="dropdown">
            <a href="#" data-bind="text: Name, value: Id, click: function() { $root.selectedRequestorName(Name); }"></a>
          </li>
        </ul>
     </div>
  </div>
  <div>
    <button id="Save" type="submit" class="btn btn-default btn-success">Create</button>
  </div>
4

3 回答 3

0
[HttpPost]
    public JsonResult SaveDetails(String selectedRequestorName)
    {
        int id = -1;

        return Json(id, "json");
    }

如上所述,将 selectedRequestorName 的类型从 Requestor 更改为 String 应该可以工作。

注意未测试。但如果有帮助,请告诉我。

于 2014-03-10T23:14:31.033 回答
0

$('#Save').click(),请您换行

数据:ko.toJSON(viewModel.selectedRequestorName)

数据:ko.toJSON(viewModel.selectedRequestorName())

希望,这会有所帮助。

于 2014-08-21T03:23:20.510 回答
0
  • 在您的控制器上创建一个接受 selectedRequestorName(字符串?)作为参数的操作方法。
  • 在您的淘汰视图模型中创建一个函数,该函数从 ko vm 中读取 selectedRequestorName,将其 JsonStringify 并通过 ajax 将其传递回上述操作方法。
于 2014-03-10T23:12:55.463 回答