【问题标题】:Knockout.js unable to call from html form in mvcKnockout.js 无法从 mvc 中的 html 表单调用
【发布时间】:2013-02-27 18:36:02
【问题描述】:

我刚刚开始使用 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)如何将数据从脚本传输到我的控制器动作?

提前致谢!!

【问题讨论】:

    标签: c# javascript html asp.net-mvc knockout.js


    【解决方案1】:

    你可以使用KnockOut mapping 做类似的事情:

    型号

    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"))
    

    【讨论】:

      【解决方案2】:

      这是一个使用原生 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 框架“自动”绑定到您的视图模型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-08
        • 1970-01-01
        • 2012-08-18
        • 2010-10-15
        相关资源
        最近更新 更多