Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 600
user3024496 Avatar asked Nov 23 '13 09:11

user3024496


People also ask

How to pass object through ajax?

You may pass an object to the data option in $. ajax . jQuery will send this as regular post data, just like a normal HTML form.

How do I pass a JavaScript model?

You can pass the model data into the java script file in these ways (1). Just set the value in hidden field and access the value of hidden field in java script. (2). And pass the value using function parameter.

How to pass object in ajax call to controller?

The URL for the jQuery AJAX call is set to the Controller's action method i.e. /Home/AjaxMethod. A JSON object named Person is created and the value of the TextBox is assigned to the Name property. The Person JSON object is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.

What is post method in Ajax?

Sends an asynchronous http POST request to load data from the server. Its general form is: jQuery. post( url [, data ] [, success ] [, dataType ] ) url : is the only mandatory parameter.


1 Answers

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.

like image 148
Snesh Avatar answered Oct 26 '22 23:10

Snesh