2

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.

11
  • What are the contents of class MyModel? Commented Sep 17, 2019 at 16:51
  • They are simple class attributes id int school_id int uniruq style_id int colour_id int image_type char(1) last_update smalldatetime last_update_by varchar(15) Commented Sep 17, 2019 at 16:54
  • 1
    You will need to create a view model that contains a list of the MyModel classes and then bind that view model to the view. Commented Sep 17, 2019 at 16:57
  • 1
    There would be no need to use Javascript, model will be posted back with form. Can you show the html of your table? Commented Sep 17, 2019 at 17:32
  • 1
    as per your table html, there will be only a display of school_id, you cant edit anything. any input field missing? Commented Sep 17, 2019 at 17:59

2 Answers 2

2

Since you are using a list, foreach loop won't work to hold and post back the values of model. you would have to use for loop with indexer to create html elements for all the fields, change your table html as below:

change your model type to List, indexer won't work with IEnumerable

Edit: Html.DisplayFor will not post back the value, an input field is required to do so. you may use Html.HiddenFor for all the fields to achieve that as shown in the code.

@model List<MyModel>

<table>
  <tr><th> @Html.DisplayNameFor(model => model.school_id) </th></tr>
@for(int i = 0; i < Model.Count; i++)
{
  <tr>
        <td>
          @Html.DisplayFor(m=> m[i].school_id)
          @Html.HiddenFor(m=> m[i].school_id)
       </td>
  </tr>
}
</table>

and decorate your Save method with ActionName and HttpPost attributes, action name should be same as given in form definition in the view:

[ActionName("Index")]
[HttpPost]
public ActionResult Save(List<MyModel> myModel){
   ...
}

On button btnSend click it will post the model back to Save method, no need of any javascript.

Sign up to request clarification or add additional context in comments.

7 Comments

I am using IEnumerable not List, that's why I used foreach loop. you can now look at the post, I have included all the source code
foreach loop will not help you to post back the model values, make changes as per the solution given in the answer to fix the problem.
thanks, i changed the foreach loop to forloop, It is only getting the right count of rows but all the fields have null value, and I got null in my database table. Why you think is this?
you can get values only for fields those have input fields created with on the view. you are using Html.DisplayFor for all the fields, it won't post back the values. an input field is required to achieve that.
So far so good, i am getting values now except for @Html.EnumDropDownListFor which there is no HiddenFor option. I don't want to create a separate input field to copy the value, because it is in the dropdownlist itself where the user will make changes.
|
0

The endpoint expects MyModel object list but you are sending a single MyModel object. Also make sure you added [HttpPost] attribute on the top of "the public ActionResult Save "

If you can't send the list of object for some reason, you can create a new model which includes a list of MyModel.

Can you try to remove this line "var model = @Html.Raw(Json.Encode(Model))"? and just pass Model instead of model?

1 Comment

sorry, I missed to include the [HttpPost] but I had it since the beginning. How do I send MyModel object as a List is what I am not clear with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.