我有一个集成 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>