5

everybody. I'm new in asp mvc. I need to pass my model as parameter in ajax post request.

Here is my ajax post request code:

<script type="text/javascript">
        $(document).ready(function () {
            $("#contragentTable tr").click(function () {                   
                $.ajax({
                    type: 'POST',
                    url: "/Contragent/Index",
                    data: $('#form').serialize(),                              
                    dataType: 'json'                    
                });
            });
        });

</script>

This is the model

public class ContragentModel
{
    private readonly List<ContragentView> contragentList = new List<ContragentView>();

    public ContragentModel()
    {
        this.IsRowSelected = false;
    }

    public List<ContragentView> ContragentList
    {
        get
        {
            return this.contragentList;
        }
    }  

    public ContragentView SelectedContragent { get; set; }

    public bool IsRowSelected { get; set; }
}

These are controllers

public ActionResult Index()
{           
    var contragentModel = new ContragentModel();
    var contragentView = new ContragentView();
    contragentView.Id = 1;            
    contragentModel.ContragentList.Add(contragentView);           

    return View(contragentModel);
}    

[HttpPost]
public ActionResult Index(ContragentModel model)
{           
    model.IsRowSelected = true;

    // Here exception throws, because there no items 
    model.SelectedContragent = model.ContragentList.Single(t=>t.Id== 1);

    return this.RedirectToAction("Index", model);            
}

When I pass my model in ajax post request model.ContragentList has no items. However in cshtml side it has. Does anybody know why?

Also, how can I pass model and more one int parameter in my ajax request?

This is my view

@model Transportation.Models.ContragentModel
@{
    ViewBag.Title = "";
    Layout = "~/Views/Shared/_MainLayout.cshtml";
}

@section head{
    <script type="text/javascript">    
        $(document).ready(function () {
            $("#contragentTable tr").click(function () {                   
                $.ajax({
                    type: 'POST',
                    url: "/Contragent/Index",
                    data: $('#form').serialize(),                          
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8'
                });
            });
        });

    </script>    
}

<table id="contragentTable" class="table table-hover table-bordered">
    <tr id="0" style="background-color: #ccc">        
        <th>
          @Html.ActionLink("some text1", "Index")
        </th>
        <th>
            @Html.ActionLink("some text2", "Index")
        </th>
        <th />
        <th></th>
    </tr>

    @if (@Model.ContragentList.Count > 0)
    {            
        <tr id="@index.ToString()">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>          
    }
    else
    {
        <tr>
            <td colspan="9">No data
            </td>
        </tr>
    }
</table>

<div>    
    @{ var displayStyle = @Model.IsRowSelected ? "" : "none";    
       var operationTypeGroups = Model.IsRowSelected ? Model.SelectedContragent.PriceList.GroupBy(t => t.OperationTypeId) : null;    
       var operationTypes = operationTypeGroups == null ? null : operationTypeGroups.SelectMany(t => t);

        <table id="priceTable" class="table table-hover table-bordered" style="display: @displayStyle">
            <tr id="0" style="background-color: #ccc">
                <th>

                </th>
                <th>

                </th>

                @if (operationTypes != null)
                {
                    foreach (var operationType in operationTypes)
                    {
                    <th>
                        @Html.ActionLink(operationType.OperationTypeName, "Index");
                    </th>
                    }
                }

                <th></th>
            </tr>

        </table>
    }

</div>
krillgar
  • 12,596
  • 6
  • 50
  • 86
user3024496
  • 51
  • 1
  • 1
  • 3
  • Could you show what input fields does your form contain in the view? – Darin Dimitrov Nov 23 '13 at 09:39
  • In my view I have table for displaying items in model.ContragentList". When I click in table row, ajaz request performing. But in my controller side I have no items in model.ContragentList collection. – user3024496 Nov 23 '13 at 10:40
  • input items must have name attributes , content type as mentioned in answer must be set ... @DarinDimitrov i think data property should be like { model : serializedform } – Vishal Sharma Nov 23 '13 at 10:41
  • No it's not necessary to be setting any content type if you directly serialize the form. It will use `application/x-www-form-urlencoded` by default. And no, you should not use `{ model : serializedform }`. The only requirement is to have proper names of the input fields. That's why I asked the OP to show his view in order to see how he generated the corresponding input fields. Unfortunately he didn't seemed to respond so we can only be guessing here and suggesting things without providing a constructive answer. – Darin Dimitrov Nov 23 '13 at 10:48
  • I add my view code to my question. – user3024496 Nov 23 '13 at 11:10
  • @user3024496 do you want to send links to your model..? when you serialize your form ofcourse it doesn't include links... – Vishal Sharma Nov 24 '13 at 02:55

1 Answers1

6

Please have a look on article: http://www.codeproject.com/Articles/678591/CRUD-Operations-using-Partial-V

In this article, CRUD operations are performed using jQuery AJAX calls in ASP.NET MVC 4 Application.

About your code, you need to modify below line:

            $("#contragentTable tr").click(function () {
                var modelDataJSON = '@Html.Raw(Json.Encode(Model))';

                $.ajax({
                url: "/Contragent/Index",
                type: 'POST',                   
                data: { myObject1: modelDataJSON},                              
                dataType: 'json'                    
                });
             });                   

You must provide a name to object in AJAX call and it should same as the argument name in targeted controller action method and Since you are sending JSON from client so action method should be like:

public ActionResult Index(string myObject1 ) 

Then inside action you can deserialize the JSON object and create model or whatever processing you need.

Snesh
  • 555
  • 1
  • 10
  • 20