I'm trying to pass a model class of List<> type from a view into a controller action method.
I couldn't find an already built in method from mvc to complete this task, and I am not much familiar with ajax/jquery. Few of the previously posted question doesn't really fit to my needs and couldn't get enough. Any help please.
I've a model class, I am able to populate all the data in a view, then a user will make changes to any of those data and the whole data in being displayed in the table should be send into a controller.
A method in my controller is waiting for List type of Model class.
public ActionResult Save(List<MyModel> myModel){
...
}
How can I send my model class into the method in my controller?
I tried the following js code but not working at all
Here is my Model class
public class MyModel
{
public int spi_id { get; set; }
public int s_id { get; set; }
public int st_id { get; set; }
}
Here is my View
@model IEnumerable<MyModel>
<form action="@Url.Action("Save", "Home")" method="post">
<table class="table" id="tblIe">
<tr>
<th>
@Html.DisplayNameFor(model => model.s_id)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.s_id)
</td>
</tr>
}
</table>
<input type="submit" name="send" value="Send" id="btnSend" />
<script type="text/javascript">
$(document).ready(function () {
$("#btnSend").click(function (e) {
alert("button click");
e.preventDefault();
var model = @Html.Raw(Json.Encode(Model))
$.ajax({
type: 'post',
url: '@Url.Action("Save", "Home")',
data: JSON.stringify({ myModel: model }),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
alert(data);
}
});
});
});
</script>
Here is my controller
[HttpPost]
public ActionResult Save(List<MyModel> myModel)
{
_service.SaveMyModel(myModel);
return View("Index");
}
I need to pass the entire content of this model as a LIST<> into my Save method in my Controller.
school_id, you cant edit anything. any input field missing?