简体   繁体   中英

Why is my form not populating my list on my view model?

When I build my form, my list populates correctly. However when I post back to my controller, the list SynonymTerm is null.

Here is my view model:

public class SynonymEditViewModel
{
    public string Term { get; set; }

    public List<SynonymTermEditViewModel> SynonymTerm;

    public SynonymEditViewModel()
    {
        SynonymTerm = new List<SynonymTermEditViewModel>();
    }
}

public class SynonymTermEditViewModel
{
    public string Term { get; set; }
    public string ReplacementTerm { get; set; }

    public SynonymDuplicateWarning Warning { get; set; }

    public SynonymTermEditViewModel()
    {
        Warning = new SynonymDuplicateWarning();
    }
}

public class SynonymDuplicateWarning
{
    public List<string> Terms { get; set; }

    public SynonymDuplicateWarning()
    {
        Terms = new List<string>();
    }
}

A simplified version of the view:

Edit.cshtml

@model MyProject.ViewModels.Synonyms.SynonymEditViewModel
<div class="form-group">
    <div class="col-md-2">
        @Html.LabelFor(model => model.Term)
    </div>
    <div class="col-md-10">
        @Html.HiddenFor(model => model.Term)
        @Html.DisplayFor(model => model.Term)
    </div>
</div>

<table id="terms-table">
    <tbody>
        @Html.EditorFor(model => model.SynonymTerm)
    </tbody>
</table>

EditorTemplates/SynonymTermEditViewModel.cshtml

@model MyProject.ViewModels.Synonyms.SynonymTermEditViewModel
<tr>
    <td>
        @Html.TextBoxFor(model => model.Term)
        @Html.ValidationMessageFor(model => model.Term)

        @Html.EditorFor(model => model.Warning)
    </td>
</tr>

Here is the form data pulled from the browser request.

Term:Cat
SynonymTerm[0].Term:Feline

This data is passed to this controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(SynonymEditViewModel synonym)
{
    if (ModelState.IsValid)
    {
        //breakpoint here
        var dbSynonym = db.Synonym_Replacement_Term.Find(synonym.Term);
        Mapper.Map(synonym, dbSynonym);
        db.SaveChanges(User.Identity.Name, Request.ServerVariables["REMOTE_ADDR"]);
        return RedirectToAction("Index");
    }

    return View(synonym);
}

The expected behavior is SynonymTerm is a list containing 1 object with Term="Feline" , and all other properties having default/constructed values. Is there any reason SynonymTerm would be null?

I found the answer. In my ViewModel, I needed to add a getter/setter for the list:

public List<SynonymTermEditViewModel> SynonymTerm { get; set; }

Apparently they're required for the reflection used by MVC, according to this similar question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM