3

我正在尝试让 knockout.js 库和 knockout.mapping.js 库在我的 MVC4 应用程序中工作。我正在使用控制器来生成视图。剃刀视图将模型转换为 JSON 字符串,然后我使用映射插件在我的 MV 中获取我的 JSON 模型。那部分一切正常。如果我向控制器中的模型添加一些值,它们就会显示在我的视图中。我遇到的问题是将 WebApi 控制器发回给我。一旦我得到它,它就不会转换回我的可序列化模型。这是我所拥有的:

<script type="text/javascript" src="/Scripts/knockout-2.1.0.debug.js"></script>
<script type="text/javascript" src="/Scripts/knockout.mapping-latest.debug.js"></script>
<script type="text/javascript">
function SearchModel() {
    var self = this;
    var baseUri = '/Api/searchsubscriber/FindSubscriber';

    self.search = function (formElement) {
        debugger;
        var myJSONString = JSON.stringify(ko.mapping.toJS(formElement));
        alert(myJSONString);
        $.ajax({
            type: "POST",
            url: baseUri,
            data: myJSONString
        }).done(updateSearchResults);

    };

    updateSearchResults = function (data) {
        debugger;
        var jsonString = JSON.stringify(data);
        alert(jsonString);
    };
};
$(function () {
    debugger;
//in my actualy view it looks like this
//var jsonModel = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';
    var jsonModel = '{"SubscriberNum":null,"PersonCode":null,"ClientCode":null,"LastName":"TEST","FirstName":"H","MI":null,"DOB":null,"StartDt":null,"EndDt":null,"GroupNum":null}';
    var mvcModel = ko.mapping.fromJSON(jsonModel);

    var myViewModel = new SearchModel();
    var g = ko.mapping.fromJS(myViewModel, mvcModel);

    ko.applyBindings(g);
});
</script><code>

这是我的模型

[Serializable]
public class SearchSubscriberFields //: SearchSubscriberResults
{
   //public List<SearchSubscriberResults> Results { get; set; }
   public string SubscriberNum { get; set; }
   public string PersonCode { get; set; }
   public string ClientCode { get; set; }
   public string LastName { get; set; }
   public string FirstName { get; set; }
   public string MI { get; set; }
   public string DOB { get; set; }
   public string StartDt { get; set; }
   public string EndDt { get; set; }
   public string GroupNum { get; set; }
}

这是我的 ApiController

[Authorize]
public class SearchSubscriberController : ApiController
{
    MyService _service = new MyService();

    [HttpPost]
    public SearchSubscriberFields FindSubscriber(SearchSubscriberFields search)
    {
        if (search != null)
        {
            SearchSubscribersRequest request = new SearchSubscribersRequest();

            request.Credentials = new Credentials() { Username = User.Identity.Name };

            request.SubscriberNum = Utility.FormatString(search.SubscriberNum).ToUpper();
            request.PersonCode = Utility.FormatString(search.PersonCode).ToUpper();
            request.ClientCode = Utility.FormatString(search.ClientCode).ToUpper();
            request.LastName = Utility.FormatString(search.LastName).ToUpper();
            request.FirstName = Utility.FormatString(search.FirstName).ToUpper();
            request.MI = Utility.FormatString(search.MI).ToUpper();

            SearchSubscribersResponse response = _service.SearchSubscribers(request);

            if (response.Errors.Count < 1)
            {
                return search;
            }
       }
        return search;
    }
}

所以,从我看过的每一个例子来看,这都应该有效。如果我将 api 控制器中的对象更改为FindSubscriber(JObject search)我可以看到我得到一个 JSON 字符串。Fiddler 显示它正在发送一个 JSON 字符串。从提琴手:

POST http://localhost:60248/Api/searchsubscriber/FindSubscriber HTTP/1.1
Accept: */*
Content-Type: application/x-www-form-urlencoded
X-Requested-With: XMLHttpRequest
Referer: http://localhost:60248/Subscriber/Search
Accept-Language: en-US,es-DO;q=0.5
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:60248
Content-Length: 157
Connection: Keep-Alive
Pragma: no-cache
{"SubscriberNum":null,"PersonCode":null,"ClientCode":null,"LastName":"TEST","FirstName":"H","MI":null,"DOB":null,"StartDt":null,"EndDt":null,"GroupNum":null}

我只是没有在我的控制器中得到可以返回SearchSubscriberFields对象的结果。

任何想法都非常感谢。

4

2 回答 2

1

您应该使用 ko.mapping.toJSON 还需要正确配置 jQuery.Ajax,现在它会像 html 表单一样发布它,您的 MVC 控制器不会理解这一点。

像这样的东西应该工作

MyApp.utils = {
    post: function (url, data, success) {
        $.ajax({
            url: url,
            type: "POST",
            dataType: "JSON",
            contentType: "application/json; charset=UTF-8",
            data: ko.mapping.toJSON(data),
            success: success
        });
    }
};
于 2012-12-12T15:18:32.057 回答
1

我发现我的问题是我的服务器模型具有 [Serializable] 属性,因此当我在剃刀视图中对其进行序列化时,它也在对支持字段进行序列化。这应该很明显,但我错过了。因此,一旦我发回我的模型,它也会发回那些绑定字段,因此无法映射到我的模型。我将此添加到 Global.asmx

        //This sets the JSON serializer to ignore the backing fields
        JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings();
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;
于 2012-12-26T15:41:58.957 回答