无法使用ajax将模型从View传递给控制器

时间:2014-03-06 09:28:10

标签: c# jquery ajax asp.net-mvc

首先我可以搜索,我发现了这样的问题:(Passing Model from view to controller using Jquery Ajax

但是当我尝试制作类似于标记答案的内容时,我收到有关circular reference的错误 所以我要求任何帮助将模型从View发送到Controler: 这是我的观点:

@model magazyn.Models.DeviceUsage

@{
    ViewBag.Title = "Return";
    //Layout = "~/Views/Shared/_Layout.cshtml";
    var val = Json.Encode(Model);
}

<h2>Return</h2>
<script>
    $(document).ready(function () {
        $('.z').on('click', function (event) {
            event.preventDefault();
            var check=@Html.Raw(Model)
            $.ajax({
                url: "/DeviceUsage/Return",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: 'html',
                data: '{dev:' + JSON.stringify(check) + '}',
                error: function (data) {
                    alert("wystąpił nieokreślony błąd " + data);
                },
                success: function (data) {
                    $('.modal-body').html(data);
                }
            })
        })
    });
</script>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>DeviceUsage</h4>
    <hr />
    @Html.ValidationSummary(true)
    <div class="input-group">
        <div class="input-group-addon">
            @Html.LabelFor(model => model.StorageId, "Gdzie oddałeś?", new { @class = "control-label col-md-2" })
        </div>
        <div class="">
            @Html.DropDownList("StorageId", null, new {@class="form-control" })
            @Html.ValidationMessageFor(model => model.StorageId)
        </div>
    </div>


    @Html.HiddenFor(model => model.DeviceInstanceId)

    <div class="input-group" style="padding-top:5px">       
            <input type="submit" value="Save" class="btn btn-default z" />
    </div>
</div>
}

和我的控制员:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Return(DeviceUsage dev)
    {
        if(dev.StorageId==3)
        {
            ModelState.AddModelError("", "Nie można oddać na własne biurko");
            ViewBag.StorageId = new SelectList(unitOfWork.storageRepository.Get(), "Id", "Name", dev.StorageId);
            return PartialView(dev);
        }
        dev.UserId = 1;
        unitOfWork.deviceUsageRepository.Update(dev);
        unitOfWork.Save();
        return RedirectToAction("MyDevices");
    }

我要求任何建议,代码片段可以帮助我解决这个问题。

@Update

取消注释var val= Json.Encode(Model); 错误:

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.DeviceInstance_445E26162DD165393D1CB531A60BA066C466C22965B1714E8F224391398180CA'.

评论 Uncaught ReferenceError: System is not defined 尝试字符串化时会抛出上面的错误

2 个答案:

答案 0 :(得分:1)

我怀疑以下代码行:

var check=@Html.Raw(Model)
data: '{dev:' + JSON.stringify(check) + '}'

你可以试试下面的代码吗?

    $.ajax({
        url: "/DeviceUsage/Return",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ dev:
           DeviceInstanceId: $('#DeviceInstanceId').val(),
           UserId: "1",
           StorageId: $('#StorageId').val()
        }),
        error: function (data) {
            alert("wystąpił nieokreślony błąd " + data);
        },
        success: function (data) {
            $('.modal-body').html(data);
        }
    });

答案 1 :(得分:0)

尝试使用

data: $('#FormId').serialize()

并为您的表单提供ID

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

    }

您的ajax通话成为

$.ajax({
                url: "/DeviceUsage/Return",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: 'html',
                data: $('#FormId').serialize(),
                error: function (data) {
                    alert("wystąpił nieokreślony błąd " + data);
                },
                success: function (data) {
                    $('.modal-body').html(data);
                }
            })