简体   繁体   中英

How to get data for knockout in partial view?

I have a main view that when clicked edit button bellow function is called:

function ShowEditRecord(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$.ajax(
    {
        url: '/Home/TestEdit/'+dataItem.Id.toString(),
        contentType: 'application/html; charset=utf-8',
        type: 'Get',
        dataType: 'html'
    })
.success(function(result)
{ $('#EditTestSection').html(result); })

Now my partial view working with knockout, my partial view is :

@model KendoSample.Models.Test

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "frm" }))
{

    <legend>Person</legend>

     <input  type="hidden"  id="Id" name="Id" data-bind='value: Id, uniqueName:true'   class='required' />

    <div class="editor-label">
      <label for="Name"/>
    </div>
    <div class="editor-field">
    <input  id="Name" name="Name"  data-bind='value: Name, uniqueName: true'  type="text" class='required'/>
        @Html.EditorFor(model => model.Name);
    </div>

    <div class="editor-label">
      <label for="Family"/>
    </div>
    <div class="editor-field">
    <input  id="Family" name="Family"  data-bind='value: Family, uniqueName: true'  class='required'/>
    </div>

   }
   <input id="btnSubmits" type="button" value="btnSubmit" />
   <script type="text/javascript" src="~/Scripts/knockout-3.0.0.js"/>
   <script type="text/javascript">
   $('#btnSubmits').on('click',function() {
    alert(viewModel.Name().toString());
    });
    var viewModel={
    Id:ko.observable(@Html.Raw(Model.Id.ToString())),
    Name: ko.observable(@Html.Raw(Model.Name.ToString())),
    Family: ko.observable(@Html.Raw(Model.Family.ToString()))
   }
   ko.applyBindings(viewModel);
  </script>

My controller code is :

 public ActionResult TestEdit(Int64 Id)
    {
        var modelItem=getT().Where(a => a.Id == Id).FirstOrDefault();
        return View (modelItem);
    }

Now, i want fill view model of knockout when partial view is rendered.

I using bellow code for bind model to knockout viewModel:

var viewModel={
    Id:ko.observable('@Html.Raw(Model.Id.ToString())'),
    Name: ko.observable('@Html.Raw(Model.Name.ToString())'),
    Family: ko.observable('@Html.Raw(Model.Family.ToString())')
}
ko.applyBindings(viewModel);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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