1

I'm having some trouble getting my ViewModel to return a non-null object in the base model property in my controller's Create action postback. I currently have another page that is doing the exact same operations on another model that has almost the same properties and that form is working perfectly, so I feel like I'm missing something basic, though I can't place what is wrong.

Here's my ViewModel with my Base class:

public class SystemFailureActionViewModel
{
    /// <summary>
    /// View model class for adding and modifying SystemFailureActions
    /// </summary>
    public SystemFailureAction action { get; set; }

    //properties
    public int TypeID { get; set; }
    public string TypeDescription { get; set; }
    public bool Assigned { get; set; } 

    public SystemFailureActionViewModel() { }

    public SystemFailureActionViewModel(SystemFailureAction action)
    {
        this.action = action;
    }

    //Collections for views
    public IEnumerable<SelectListItem> EditSystemFailiureTypesList { get { return ModelListProvider.FilteredSystemFailureTypeList; } }
    public IEnumerable<SelectListItem> DetailsSystemFailiureTypesList { get { return ModelListProvider.FullSystemFailureTypeList; } }
}

[MetadataType(typeof(SystemFailureActionMetadata))]
public partial class SystemFailureAction
{
    private class SystemFailureActionMetadata
    {
        /// <summary>
        /// ID for this failure action
        /// </summary>
        public int ID { get; set; }

        /// <summary>
        /// Action Description
        /// </summary>
        [Required]
        [StringLength(200)]
        [DisplayName("Action Description")]
        public string Description { get; set; }
    }
}

Here's my Controller Add and Add Postback methods:

public ActionResult Add()
    {
        SystemFailureAction action = new SystemFailureAction();
        action.Description = "";
        populateSystemFailureActionData(action);
        return PartialView("Form", new SystemFailureActionViewModel(action));
    }


    [HttpPost]
    public ActionResult Add(SystemFailureActionViewModel viewModel, string[] selectedTypes, FormCollection collection)
    {
        SystemFailureAction newAction = viewModel.action;

        if (!ModelState.IsValid)
        {
            populateSystemFailureActionData(newAction);
            return PartialView("Form", new SystemFailureActionViewModel(newAction));
        }

        try
        {
            //Insert the new failure action type 
            context.SystemFailureActions.InsertOnSubmit(newAction);
            context.SubmitChanges();

            //Insert the failure type mappings
            updateSystemFailureAssociationData(newAction, selectedTypes);
            context.SubmitChanges();

            //Return the new data
            populateSystemFailureActionData(newAction);
            return PartialView("Done", new SystemFailureActionViewModel(newAction));
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.Message);
            populateSystemFailureActionData(newAction);
            return PartialView("Form", new SystemFailureActionViewModel(newAction));
        }           
    }      

And finally here is my form, it is being loaded into a Jquery dialog and the postback is being done via Ajax.

  @using (Ajax.BeginForm(new AjaxOptions
{
    HttpMethod = "Post",
    UpdateTargetId = "formDialog",
    InsertionMode = InsertionMode.Replace,
    OnSuccess = "onDialogDone()"
}))
{
    @Html.ValidationSummary(true)
    <div>
        <div class="editor-label">
            @Html.LabelFor(model => model.action.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.action.Description)
        </div>
    </div>
    <div class="categoryFieldSet">
        <fieldset>
            <legend>Mechanical System Failure Categories</legend>
            <div class="editor-field">
                <table>
                    <tr>
                        @{
                            int count = 0;
                            List<ManageMAT.ViewModels.SystemFailureActionViewModel> types = ViewBag.Types;

                            foreach (var type in types)
                            {
                                if (count++ % 3 == 0)
                                {
                                    @: </tr> <tr>
                                }
                                @: <td>
                                    <input type="checkbox"
                                           id="selectedTypes + @type.TypeID"
                                           name="selectedTypes"
                                           value="@type.TypeID"
                                           @(Html.Raw(type.Assigned ? "checked=\"checked\"" : "")) />
                                    <label for="selectedTypes + @type.TypeID">@type.TypeDescription</label>
                                @:</td>
                            }
                        @:</tr>
                        }
                </table>
            </div>
        </fieldset>
    </div>
}

If you're wondering what the ViewBag.Types logic is in the form it is related to this question I asked earlier.

Edit:

I checked the ModelState error and the exception I'm getting is

"The parameter conversion from type 'System.String' to type Models.SystemFailureAction' failed because no type converter can convert between these types."

I also removed the logic that adds the Failure types and I'm still receiving the same issue. So it appears the problem is coming from mapping the Viewmodel.action.Description to the action.

1 Answer 1

2

The problem is the following property on your SystemFailureActionViewModel:

public SystemFailureAction action { get; set; }

In ASP.NET MVC action and controller are kinda reserved words. They are part of every route. And if you have a property called this way it conflicts with the string value which is pointing to the action name and which obviously cannot be bound to a complex SystemFailureAction type.

So to fix the problem simply rename this property on your view model:

public SystemFailureAction FailureAction { get; set; }
1
  • Excellent, I didn't even think of that being the issue. That solved my problem. I wonder why that doesn't throw some kind of compile time error, or even show up as a reserved keyword in VS?
    – Philter
    Jan 25, 2012 at 21:46

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.