0

对不起,我的英语不好。我有个问题。当我从视图传递 JSON 数据时,出现错误:“路径中有非法字符。” 我的控制器:

public class HomeController : Controller
    {
        private WeaponContext _db = new WeaponContext();
    public ActionResult Index()
    {
        var allWeapons = _db.Weapons.ToList<Weapon>();
        var allWeaponsJSON = JsonConvert.SerializeObject(allWeapons);
        return View(allWeaponsJSON);
    }
}

还有我的 index.html:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using TestingApp.Models
@model IEnumerable<Weapon>
    <h3>Weapons</h3>
        <table class="center">
        <tr><td><p><h3>Name of weapon</h3></p></td><td><p><h3>Created</h3></p></td><td><p><h3>Description</h3></p></td></tr>
        <tbody data-bind="foreach: model.Weapon"></tbody>
             <tr><td><span data-bind="text: Title"></span></td><td><span data-bind="text: Created"></span></td><td><span data-bind="text: Description"></span></td></tr>

        </table>
<script type="text/javascript" src='@Url.Content("~/Scripts/knockout-2.3.0.js")'>
    $(document).ready(function () {
        var viewWeapons = {};
        $.getJSON("/index", function (data) {
            viewWeapons = ko.mapping.fromJSON(data);

        });
    });
    ko.applyBindings(viewWeapons);
</script>
@section Footer {
    Все права защищены. Vlad Corp. 2013.
}

怎么了?

4

1 回答 1

1

你需要返回JsonResult

public JsonResult Index()
{
    var allWeapons = _db.Weapons.ToList<Weapon>();
    return Json(allWeapons, JsonRequestBehavior = JsonRequestBehavior.AllowGet );
}

你需要设置, JsonRequestBehavior = JsonRequestBehavior.AllowGet,如果你想允许'GET'

于 2013-10-26T16:45:51.693 回答