user3024496
user3024496

Reputation: 51

How to pass model in ajax post request?

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>

Upvotes: 5

Views: 43789

Answers (1)

Snesh
Snesh

Reputation: 555

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.

Upvotes: 6

Related Questions