繁体   English   中英

Knockout.js无法从MVC中的HTML表单调用

[英]Knockout.js unable to call from html form in mvc

我刚刚开始使用Knockout.js。 我已经阅读了有关在mvc中使用基因敲除法从数据库访问数据的各种教程,但是没有任何效果。 以下是我的表格:-

    <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映射执行以下操作:

模型

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);
}

视图

@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);
}

视图

<!-- 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.NET MVC框架“自动”绑定到您的视图模型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM