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>