0

First of all I can search and I found questions like this: (Passing Model from view to controller using Jquery Ajax

But when I'm trying to make something like in marker answer I receive error about circular reference So I'm asking for any help in sending Model from View to Controler: Here is my View:

@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>
}

and my controller:

[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");
    }

I'm asking for any suggestions, code snippets which could help me in solving this problem.

@Update

With uncommented var val= Json.Encode(Model); Error:

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

With commented Uncaught ReferenceError: System is not defined above error is thrown when trying to stringify

Community
  • 1
  • 1
szpic
  • 4,346
  • 15
  • 54
  • 85

2 Answers2

1

I doubt on following line of code:

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

can you try the below code?

    $.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);
        }
    });
Ashwini Verma
  • 7,477
  • 6
  • 36
  • 56
  • `({ dev: DeviceInstanceId: $('#DeviceInstanceId').val(), UserId: "1", StorageId: $('#StorageId').val() }),` This part of code couses many problems with `({ ; and ,` – szpic Mar 06 '14 at 09:54
  • try using hardcoded value for testing. DeviceInstanceId:"1",UserId:"1",StorageId:"2". then if it works you can think about getting it from existing form fields. – Ashwini Verma Mar 06 '14 at 09:59
  • Yeah it works when I remove [ValidateAntiForgeryToken] from controler – szpic Mar 06 '14 at 10:12
  • And To fix error in your code add curly brackets like here: `{ dev: {DeviceInstanceId: $('#DeviceInstanceId').val(), UserId: "1", StorageId: $('#StorageId').val() } }` And then the code is working :) – szpic Mar 06 '14 at 10:19
0

Try using

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

and give id to your form like

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

    }

Your ajax call becomes

$.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);
                }
            })
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60
  • serialize return this: __RequestVerificationToken=25waYRlP806vG2Rgrl3malpij8P6nnCqI8sGZltDxsZ_asQAphD6BTWvfiXLx1vETk5H25K8m_YCIXIPwqzmwgRUziVZL_e0J4RUO8yiWLcrwJsRpwt7rtbRMh0eaJrQ0&StorageId=3&DeviceInstanceId=1 So I only need to cut it now – szpic Mar 06 '14 at 10:05
  • reason u r getting __RequestVerificationToken ...... is u r using [ValidateAntiForgeryToken] at action – Nitin Varpe Mar 06 '14 at 10:12
  • http://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken check link might help – Nitin Varpe Mar 06 '14 at 10:13