1

I have model that is a list of another model such that ModelList : ModelSingle In my razor view I am using

@model somenamespace.ModelList
@Html.EditorForModel()

This iterates though each ModelSingle and returns an EditorTemplate that is strongly typed to ModelSingle.

@model somenamespace.ModelSingle
@using(Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "formname" + Model.ID}))
{
    @Html.AntiForgeryToken()
    @Html.EditorFor(p => p.SomeField)
    @Html.EditorFor(p => p.AnotherField)
}

Each of these templates contains a form that can be used to edit the single model. These are posted individually with my controllers method expecting

public ActionResult(ModelSingle model)

The problem I'm having is that the model is not binding correctly. With a Model as such

public class ModelSingle()
{
    public string SomeField { get; set; }
    public string AnotherField { get; set; }
}

the EditorTemplate is being told that it was part of a list so I get

<Form>
    <input name="[0].SomeField"/>
    <input name="[0].AnotherField"/>
    <input type="submit" value="Update"/>
</Form>

I can't simply bind to the ModelList as it's not naming ModelList[0].SomeField and even if it was I don't think that would work for anything but the first item.

Is there anyway to make the EditorTemplate ignore the fact that it's model was part of a list or force a DropDownListFor, EditorFor etc.... to just use the field name without prepending the [i].

I know I can force a Name="SomeField" change but I'd rather have a solution that will reflect any changes made in the Model class itself.

EDIT - As Requested added a simplified example of the View and EditorTemplate being used.

1
  • Can you show the @model tags at the top of your view and templates?
    – Pat Burke
    Mar 5, 2014 at 15:41

1 Answer 1

2

The problem is related to a mismatch between the input names generated by your page model (which is a list), and the model expected by your action, which is a single item from your list.

When rendering a list, the default behavior is to render the indexed names like you've shown to us (the [#] notation). Since you want to be able to post any arbitrary item from the list, you won't know ahead of time what index is used. When the model binder looks at the request for your single object, it does not attempt to use the index notation.

I don't know what your requirements are from the user perspective - e.g. whether or not a page refresh is desired, but one way to accomplish this is to provide a jQuery post for the specific item being posted:

// pass jquery form object in
var postItem = function($form) {
    var postBody = {
        SomeField: $form.find('input selector')    // get your input value for this form
        AnotherField: '' // another input select for this item
    }

    $.ajax({
        url:'<your action url>', 
        type: 'POST',
        contentType:"application/json; charset=utf-8",
        data: JSON.stringify(postBody),
        dataType: 'json',
        success: function(response) {
            // do something with returned markup/data
        }
    });
}

You are manually serializing a single instance of your model with a json object and posting that. What you return from the action is up to you: new markup to refresh that specific item, json data for a simple status, etc.

Alternately, you can consider manually looping over the items in your collection, and using Html.RenderPartial/Html.Partial to render each item using your View template. This will short-circuit the name generation for each item, and will generate the names as if it's a single instance of ModelSingle.

Finally, a quick (but kind of ugly) fix would be to have your action method take a list of ModelSingle objects. I don't suggest this.

Edit: I missed some important aspects of posting json to an mvc action

Edit2: After your comment about hardcoded names, something like this could help:

    var inputs = $form.find('all input selector');
    var jsonString = '{';
    $.each(inputs, function(index, element) {
        var parsedName = element.attr('name').chopOffTrailingFieldName();
        jsonString += parsedName + ":'" + element.val() + "',";
    });
    jsonString += '}';
8
  • Thanks Maf. I am actually posting the items via Jquery Ajax (Although with a simple Serialize of the entire form at the moment). When a single item is updated the action method in the controller returns the EditorTemplate with the new values (Or any errors). The current EditorTemplate is then replaced with the new one and Jquery rebinds to intercept the submit. I get that the Parent is strongly typed to a list but the EditorTemplate is strongly typed to the single item as is the post method so I don't understand why it's insisting on an indexed name.
    – Oli
    Mar 5, 2014 at 16:13
  • The simple serialize is the problem: it just uses the names created by mvc. The distinction is that the manual serialization will give you the names required to bind a single ModelSingle object.
    – maf748
    Mar 5, 2014 at 16:18
  • 1
    Regarding the indexed name: long story short, the parent page is rendering a list, so it is creating the indexes for each item. Since you're using the Html.EditorFor* method, the Editor template transparently receives the index prefix from the parent view when rendering. By using the second option (render partial), the context from the parent view is broken so the EditorTemplate no longer has the prefix used to build the indexed names.
    – maf748
    Mar 5, 2014 at 16:22
  • I was hoping to avoid the hard coding names route in case a field name is for some reason changed in the model. I can force the name from within the EditorTemplate if need be. I'd just rather get to the cause of the issue than hack a workaround if possible. If not then manually entering the names (Or adding class selectors as per your example) it will have to be.
    – Oli
    Mar 5, 2014 at 16:26
  • 1
    Bingo - Your explanation on EditorFor vs Partial breaking the index was spot on. Changing Html.EditorForModel() to foreach(var singleModel in Model){ Html.Partial(singleModel.GetType().Name, singleModel) } Made everything work like a charm. Thanks for the help. Much appreciated.
    – Oli
    Mar 5, 2014 at 16:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.