Multiple forms in ASP.NET MVC

前端 未结 5 2219
生来不讨喜
生来不讨喜 2020-12-20 16:46

Context
Let`s say i have:
In layout Site.Master:

5条回答
  •  长情又很酷
    2020-12-20 16:58

    If you have two simple forms, you can use this aproach:

    You create two different partial views.

    @model CustomerInfoModel
    @using (Ajax.BeginForm("CustomerInfo", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "info", @class = "form-horizontal" }))
        {
        
        
        
        }
    

    and

    @model CustomerPasswordChangeModel
    @using (Ajax.BeginForm("CustomerPasswordChange", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "change", @class = "form-horizontal" }))
    {
    
    
    
    }
    

    In your parent view,

    @Html.Partial("CustomerInfo", Model.CustomerInfo)
    

    and

    @Html.Partial("CustomerPasswordChange", Model.CustomerPasswordChange)
    

    In Controller:

        [HttpPost]
        public ActionResult CustomerInfo([Bind(Include = "Name,Email")] CustomerInfoModel model)
        {
            if (ModelState.IsValid)
                return new Json(new { success=true, message="Updated.", errors=null);
    
    // do you logic
    
            return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
        }
    
        [HttpPost]
        public ActionResult CustomerPasswordChange([Bind(Include = "OldPassword,NewPassword")] CustomerPasswordChangeModel model)
        {
            if (ModelState.IsValid)
                return new Json(new { success=true, message="Updated.", errors=null);
    
    // do you logic
    
            return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
        }
    

    This will do what you want to do.

    Note: getHtmlContent method is just generating an error message to be displayed on page. Nothing so special. I may share it if required.

提交回复
热议问题