1

I have a view model that contains following codes:

public IEnumerable<MvcInternetShop.Models.DomainModels.Group> Groups { get; set; }
public MvcInternetShop.Models.DomainModels.Group Group { get; set; }

and I have an action for add a group:

public ActionResult AddGroup(Group model)
    {
        if (ModelState.IsValid)
        {
            if (gr.Add(model)) // gr is a GroupRepository for CRUD.
                return JavaScript("notif({type: 'info',msg: 'Your Group Registerd.',width: 'all',height: 100,position: 'center'});");
            else
                return JavaScript("notif({type: 'error',msg: 'Error.Try again!.',width: 'all',height: 100,position: 'center'});");
        }
        else
        {
            return JavaScript("notif({type: 'error',msg: '" + ModelState.GetErrors() + "',width: 'all',height: 100,position: 'center',modal:true});");//GetError() is a  myExtension method.
        }
    }

now in the view, I wanna post a group to the this action. I'm using a form for this:

@using (Ajax.BeginForm("AddGroup", "Admin", new AjaxOptions { HttpMethod="Post",Url="/Admin/AddGroup"}))
{
    @Html.TextBoxFor(p=>Model.Group.Name)//Model is a viewmodel that contains Group and Groups property.
    @Html.ValidationMessageFor(p => Model.Group.Name)  
    <button type="submit" class="button">Add group</button>}

but when I run that,the view returns a null model to the AddGroup action. in fact the name of textbox is not 'Name'. it is 'Group.Name'and because of that the action can not recognize the model properly. can anyone help me to resolve this problem?

alirezafc
  • 152
  • 1
  • 3
  • 13
  • 1
    Change your POST method to `public ActionResult AddGroup(YourModel model)` where `YourModel` is the same model you use in the view, and change it to `public ActionResult AddGroup([Bind(Prefix = "Group")]Group model)` –  Apr 23 '18 at 09:10
  • 1
    As a side note, view models do not contain data models - they contain the properties of the data models you need in the view. –  Apr 23 '18 at 09:13
  • thanks a lot Stephen.it works. – alirezafc Apr 23 '18 at 09:22

0 Answers0