Knockout.js无法在mvc中从html表单调用

本文关键字:中从 html 表单 调用 mvc js Knockout | 更新日期: 2023-09-27 18:03:23

我刚开始使用Knockout.js。我读过关于在mvc中使用knockout.js从数据库访问数据的各种教程,但没有任何效果。下面是我的表单:-

    <form  data-bind="submit: save" method="post" style="text-align: inherit;">
        <table>
            <tr>
                <td style="text-align: right">
                    Name:
                </td>
                <td>
                    <input type="text" placeholder="Enter Your name" data-bind="value: name" required /><br />
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Emp#:
                </td>
                <td>
                    <input type="text" placeholder="Enter Your Code" required data-bind="value:code" />
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Date of Birth:
                </td>
                <td>
                    <input type="date" placeholder="Enter Your Date Of Birth" data-bind="value:date" />
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Age:
                </td>
                <td>
                    <input type="number" placeholder="AGE" min="18" max="60" data-bind="value:age" /><br />
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Contact Number:
                </td>
                <td>
                    <input type="text" placeholder="Enter Your Contact Number" data-bind="value:contact" />
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Email:
                </td>
                <td>
                    <input type="email" placeholder="Enter Your Email" data-bind="value:email" />
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Address:
                </td>
                <td>
                    <input type="text" placeholder="Enter Your Address" data-bind="value: address" />
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    City:
                </td>
                <td>
                    <select>
                        <option value="city" data-bind="selectedOptions:optionselect">Noida</option>
                        <option value="city" data-bind="selectedOptions:optionselect">Mumbai</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Marital Status:
                </td>
                <td>
                    <input type="radio" name="martialStatus" value="Married" data-bind="checked:radioselect" />Married
                    <input type="radio" name="martialStatus" value="UnMarried" data-bind="checked:radioselect" />UnMarried
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    Any Employee Reffrence:
                </td>
                <td>
                    <input type="checkbox" name="referal" value="yes" data-bind="checked:checkboxchecked" />
                </td>
            </tr>
        </table>
        <div style="float: right; margin-right: 15px;">
        <input type="submit" name="submit" value="Save" />
        <button type="button" value="cancel" onclick="window.close(this);">
            Cancel
        </button>
        </div>
        </form>

我的javascript如下:-

     <script type = "text/javascript">
     var viewModel = {
   name: ko.observable(""),
    code: ko.observable(""),
   date: ko.observable(""),
   age: ko.observable(""),
   contact: ko.observable(""),
  email: ko.observable(""),
    address: ko.observable(""),
   optionselect: ko.observable(""),
   radioselect: ko.observable(""),
    checkboxchecked: ko.observable("")
    var save = function(){
     $.ajax("/Exercise/Exercise7", {
        ko.toJSON(viewModel),
        type: "post", 
        contentType: "application/json",
        success: function(result) { alert(result) }
    });
    <script>

问题是:-
1)当我运行这个应用程序的脚本不是从表单调用。2)如何将数据从脚本转移到我的控制器动作?

提前感谢!!

Knockout.js无法在mvc中从html表单调用

您可以使用KnockOut映射做类似的事情:

public class ExampleKoViewModel
{
    public string SimpleName { get; set; }
    // More properties etc here...
}
控制器

[HttpGet]
public ActionResult ExampleKo()
{
    return View();
}
[HttpPost]
public ActionResult ExampleKo(ExampleKoViewModel viewModel)
{
    // Do something with the value passed back
    string debugMessage = "Hello there " + viewModel.SimpleName;
    return View();
}
[OutputCache(Duration=0,VaryByParam="none")]
public JsonResult KnockoutViewModelTest()
{
    // Build up our view model
    var viewModel = new ExampleKoViewModel();
    viewModel.SimpleName = "Fred Bloggs";
    // Send back as a Json result
    var result = new JsonResult();
    result.Data = viewModel;
    return Json(result, JsonRequestBehavior.AllowGet);
}
<<p> 视图/strong>
@using (Html.BeginForm())
{
    <input type="text" data-bind="text: SimpleName" name="SimpleName" id="SimpleName" />
    <button type="submit" value="Save">Save</button>
}
@Ajax.KnockoutForModel(true, true, Url.Content("KnockoutViewModelTest"))

下面是一个使用本地KO &ASP。NET MVC:

public class MyViewModel
{
    public string FirstName { get; set; }
    //other properties, etc...
}

控制器方法

[HttpPost]
public JsonResult Save(MyViewModel viewModel)
{
    // do something with the data...
    string expectedName = viewModel.FirstName;
    return Json(expectedName);
}
<<p> 视图/strong>
<!-- Sample Markup... -->
<form data-bind="submit: mySubmitFunction">
    <input type="text" data-bind="text: firstName" />
    <!-- Your form will have other fields here... -->
    <button type="submit"></button>
</form>
<!-- KO ViewModel ... -->
<script type="text/javascript">
    var viewModel = function() {
        var self = this;
        //View Model properties...
        self.firstName = ko.observable();
        //View Model Events...
        self.mySubmitFunction = function() {
            //build up our data...
            //as complexity increases, consider
            //using a separate object to handle 
            //data access, etc..
            var postData = {};
            postData.FirstName = self.firstName;
            $.ajax({
                url: '@Url.Action("Save", "MyController")', //Your Controller Url
                data: postData,
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {
                    alert(data); // should be the firstName passed back from the server
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    //handle the error somehow...
                }
            });
        }
    };
    //wire up the viewModel
    $(document).ready(function(){
        var myViewModel = new ViewModel();
        ko.applyBindings(myViewModel);
    });
</script>

注意:传递给服务器的JSON将通过ASP"自动"绑定到视图模型。