I have a view where set of Images relating to certain album will be edited to change their description and to make them cover photo.
EditImageViewModel.cs
public class EditImageViewModel
{
public int ImageId{get;set;}
public string ImageUrl{get;set;}
public string ImageDes{get;set;}
public bool IsCoverPic{get;set;}
}
From one of the controller ActionResult
, I return model
to view
as
return PartialView("_ImageEditView",model);
.
model
returned above isList<EditImageViewModel>
Now in the view I display it as below:
_ImageEditView.cshtml
@model IEnumerable<EditImageViewModel>
@using(Html.BeginForm("UpdateImage","Controller",FormMethod.Post))
{
@foreach(var image in Model)
{
<img src="@image.ImageUrl"/>
@Html.TextAreaFor(m=>image.ImageDes)
@Html.RadioButtonFor(m=>image.IsCoverPic)
}
<button type="submit" class="update" value="Update"></button>
}
I have an ajax
piece of code which calls ActionResult
as below:
$('.update').on('click',function(e){
e.preventDefault();
var url=$(this).closest('form').attr('action');
var formdata=$(this).closest('form').serialize();
$.ajax({
url:url,
data:formdata,
type:'POST',
dataType:'JSON',
success:function(resp){
},
error:function(resp){
}
})
});
My Controller ActionResult
goes like this:
[HttpPost]
public ActionResult UpdateImage(List<EditImageViewModel> model)
{
//actions to be performed
}
My problem here is no matter what, the model
will always be null
in the controller, when the post occurs. The formdata
with have the data when checked in browser console. But it isn't get passed to controller method.
After going through few posts I learnt that it creates duplicate ids for multiple records in List
when foreach
is used. So I changed it to for
loop as below:
@model IEnumerable<EditImageViewModel>
@using(Html.BeginForm("UpdateImage","Controller",FormMethod.Post))
{
@for(int i=0;i<Model.Count();i++)
{
<img src="@Model[i].ImageUrl"/>
@Html.TextAreaFor(m=>m[i].ImageDes)
@Html.RadioButtonFor(m=>m[i].IsCoverPic)
}
<button type="submit" class="update" value="Update"></button>
}
But still the model
is null when received in controller. I also tried using serializeArray
instead of serialize
, but it did not help much. I referred few posts like Post 1
, Post 2
etc., but none of them solved this problem.
Ultimately, how can I pass this list of Model from
ajax
tocontroller
?