客户端数据与淘汰赛js和MVC操作方法绑定 [英] Client side data binding with knockout js and MVC action method

查看:122
本文介绍了客户端数据与淘汰赛js和MVC操作方法绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC新。所以我不知道,当页面被请求第一次那么操作方法被调用。如果我们从操作方法传递JSON话,怎么可能,我们认为,从客户端JSON和淘汰赛和绑定控件解析JSON。

i am new in mvc. so i am not sure that when page is requested first time then a action method is called. if we deliver the json from that action method then how could we hold that json from client side and parse that json by knockout and bind controls.

我碰到的asp.net MVC和淘汰赛,但这些都绑定控制一些文章在服务器端的第一个请求,并从随后的行动他们所谓的jQuery服务器端/操作方法功能,什么JSON的行动方法返回他们只是分析,并与JSON填充淘汰赛。

i came across few article on asp.net mvc and knockout but those all bind control at server side at the first request and from the subsequent action they call server side/ action method function by jquery and what json that action method return they just parse and populate knockout with those json.

所以它可以捕捉的json当页面请求的第一次淘汰赛填充视图模型。
样品code帮助将是对我很大的帮助。

so is it possible to capture json when page requested first time and populate knockout view model. help with sample code would be very helpful for me.

我们需要使用任何其他knockoutjs映射JSON和数据绑定?谢谢

do we need to use any other knockoutjs for mapping json and bind data? thanks

推荐答案

您控制器将填充这势必给ASP.net视图模型。然后在视图中您可以使用需要将C#模型序列化到JSON。在这里,我使用json.net。然后,你可以把它绑定到视图上的HTML。

Your controller would populate a model which is bound to the ASP.net view. Then in the view you would use need to serialize the c# model to json. Here I'm using json.net. Then you can bind it to the html on the view.

所以,如果你的C#模式是这样的:

So If your C# Model is this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

然后您的控制器是这样的:

And then your controller is this:

public class PersonController : Controller
{
    // GET: Person
    public ActionResult Edit(int personId)
    {
        //this is where you would load the person from your data source
        var person = _datasource.GetPerson(personId);

        return View(person);
    }
}

然后在你的观点,你会script标签内的序列化到JSON:

Then in your view you would serialise to json within a script tag:

$(function() {
    var personModel = '@JsonConvert.SerializeObject(Model)';
    ko.applyBindings(new PersonViewModel(personModel));
});

你干脆把所有的视图模型被捆绑和缩小的使用asp.net捆绑JavaScript文件。

You would put all your view models in javascript files that are bundled up and minified using asp.net bundling.

这是 PersonViewModel.js

var PersonViewModel = function (model) {
    var self = this;

    self.firstName = ko.observable(model.FirstName);
    self.lastName = ko.observable(model.LastName);

    self.save = function () {
        ...
    }
};

这篇关于客户端数据与淘汰赛js和MVC操作方法绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆