Save data of multiple models from single View in ASP.Net Core MVC

pandeygolu4200
 
on Sep 14, 2022 01:23 AM
Sample_183388.zip
1552 Views

How to save data of multiple model class in single razor view in asp.net core mvc

I have one form where 3 tabs are there i need to save data of all 3 tabs which is present in 3 class, when i combine all 3 classes in view model and then pass it to controller then ModelState.IsValid getting false and it did not save the data.

Please refer my code for better understanding.

using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace ThomosMason.Web.Models.Provider
{
    public class ProviderModel
    {
    }
   
    public class ManageProviderModel
    {
        public int? providerId { get; set; }

        [Required(ErrorMessage = "First Name is Required")]
        public string FirstName { get; set; }
        public string? MiddleName { get; set; }

        [Required(ErrorMessage = "Last Name is Required")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "DOB is Required")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]

        public DateTime? DOB { get; set; }
        // public DateTime DOB { get; set; }

        [Required(ErrorMessage = "Email is Required")]
        [EmailAddress(ErrorMessage = "Invalid Email")]
        public string Email { get; set; }

        [DataType(DataType.Date)]
        [BindProperty(SupportsGet = true)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
       
        public DateTime? StartDate { get; set; }      
        public string? TaxID { get; set; }       
        public string? PTan { get; set; }
        public string ? NPI { get; set; }
        public string? SSN { get; set; }       
        public string? Phone { get; set; }
        public string? Fax { get; set; }
        public string? AddressLine1 { get; set; }
        public string? AddressLine2 { get; set; }
        public int? StateID { get; set; }
        public int? CityID { get; set; }
        public string? Zipcode { get; set; }
        public string? Website { get; set; }
        public string Role { get; set; } = "Provider";
        public string? updatedBy { get; set; }
        public string ?createdBy { get; set; }
    }
    public class ManageProviderDocumentModel
    {
        //[Required]
        public string? UserID { get; set; }
        [Required(ErrorMessage = "Document Type is Required")]
        public long DocumentTypeID { get; set; }
        public string? DocumentName { get; set; }
        public string? Description { get; set; }
        public string? DocumentPath { get; set; }
        public string? CreatedBy { get; set; }
        //[Required(ErrorMessage = "F Type is Required")]
        public List<IFormFile> ? Files { get; set; }
        public int? FileLimit { get; set; } = null;
        public long? StateID { get; set; }
        public DateTime? IssueDate { get; set; }
        public DateTime? ExpirationDate { get; set; }
        public string? DocumentNumber { get; set; }
        public string? FileName { get; set; }
    }
    public class ProviderViewModel
    {
        public ManageProviderModel ManageProvider { get; set; }
        public ManageProviderDocumentModel? ManageProviderDocument { get; set; }
    }
}

AddProvider is method where its get failed.

using Microsoft.AspNetCore.Mvc;
using ThomosMason.Web.Models.Provider;
using ThomosMason.Web.ServiceCall;

namespace ThomosMason.Web.Controllers.Controllers
{
    public class ProviderController : Controller
    {
        IConfiguration Configuration;
        public ProviderController(IConfiguration _configuration)
        {
            Configuration = _configuration;
        }
        public IActionResult AddProvider()
        {
            return View();
        }
        [HttpPost]
        public IActionResult AddProvider(ProviderViewModel model)
        {
            if(ModelState.IsValid)
            {
                AccountApiCall accountApiCall = new AccountApiCall(Configuration["PrescriptionAPI"]);
                //model.createdBy= HttpContext.Request.Cookies["FullName"] != null ? HttpContext.Request.Cookies["FullName"].ToString() : "";
                var Response = accountApiCall.PostAPIcall<GetProviderDetailModel>(model, "provider/personaldetailsadd", HttpContext.Request.Cookies["Token"].ToString());
                //return Json(Response.message);
                if (Response.status)
                {
                    ViewBag.ProviderId = Response.data;
                    return View();                

                }
                else
                {
                    ModelState.AddModelError("CustomError", Response.message);
                    return View();
                }
            }
            else
            {
                return View();
            }           
        }        
    }
}

how can save data of ManageProviderModel and ManageProviderDocumentModel.

@model ThomosMason.Web.Models.Provider.ManageProviderModel
 
<form method="post" enctype="multipart/form-data" asp-controller="Provider" asp-action="AddProvider" class="tab-content mt-3">
    <div class="tab-pane active" id="step1">
                    <div class="provider-details-wrapper">
                        <h6>Personal Details</h6>
            <input type="hidden" name="myHiddenInput" id="myHiddenInput" value="@ViewBag.ProviderId" />
                        <div class="row">
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                    <label for="firstname">First Name</label>
                        @Html.TextBoxFor(c=>c.FirstName,new{ @class="form-control",id="firstname"})
                         <span asp-validation-for="FirstName" class="text-danger"></span>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                    <label for="middlename">Middle Name</label>
                        @Html.TextBoxFor(c=>c.MiddleName,new{ @class="form-control",id="middlename"})
                    </div>
                            </div>
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                    <label for="lastname">Last Name</label>
                        @Html.TextBoxFor(c=>c.LastName,new{ @class="form-control",id="lastname"})
                        <span asp-validation-for="LastName" class="text-danger"></span>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                    <label for="birthdate">Date of Birth</label>
                         
                       @* @Html.TextBoxFor(m => m.DOB, new{ type = "date",@class="form-control",id="datepicker"})*@
                        @Html.TextBoxFor(c => c.DOB, new { id = "dob",type = "date",@class="form-control" })
                        <span asp-validation-for="DOB" class="text-danger"></span>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                    <label for="website">Website</label>
                        @Html.TextBoxFor(c=>c.Website,new{ @class="form-control",id="website"})
                        <span asp-validation-for="Website" class="text-danger"></span>
                                    
                                </div>
                            </div>
 
                        </div>
                        <div class="d-flex justify-content-end mt-5">
                <a href="@Url.Action("List","Provider")" class="btn cancel-btn me-3">Cancel</a>
                           @* <a href="manage-provider.html" class="btn save-btn">Save & next</a>*@
                <input type="submit" class="btn save-btn" value="Save & next" id="savebtn">
                  
                        </div>
                    </div>
                </div>
                <div class="tab-pane " id="step2">
                    <div class="provider-details-wrapper">
                        <h6>License, Certifications & Documents</h6>
                        <div class="row">
                <div class="col-lg-3 col-md-4">
                    <div class="form-group">
                        <label for="doctype">Document Type</label>
                        <select class="form-control form-select" id="DocumentTypeID" name="DocumentTypeID">
                        </select>
                         
                        <select class="form-control form-select" id="documentype">
                            <option>Noida</option>
                            <option value="1"></option>
                            <option value="2"></option>
                        </select>
                    </div>
                </div>
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                    <label for="firstname">Document Name</label>
                                    <input type="text" class="form-control" id="firstname">
                                </div>
                            </div>
 
                <div class="col-lg-3 col-md-4">
                    <div class="form-group">
                        <label for="firstname">Document Number</label>
                        <input type="text" class="form-control" id="documentnumber">
                    </div>
                </div>
 
                            <div class="col-lg-3 col-md-4">
                                <label for="state">State</label>
                                <div class="form-group">
                                    <select class="form-control form-select">
                                        <option>Noida</option>
                                        <option value="1"></option>
                                        <option value="2"></option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                      
                                    <label for="isuuedate">Isuue Date</label>
                                    <input type="date" class="form-control" id="isuuedate">
                                </div>
                            </div>
                            <div class="col-lg-3 col-md-4">
                                <div class="form-group">
                                    <label for="tax">Expiration Date</label>
                                    <input type="date" class="form-control" id="tax">
                                </div>
                            </div>                                            
                        </div>
                        <div class="d-flex justify-content-end mt-5">
                            <a href="manage-provider.html" class="btn cancel-btn me-3">Back</a>
                            <a href="manage-provider.html" class="btn save-btn">Save & next</a>
                        </div>
                        <div class="d-flex justify-content-end mt-5">
                            <a href="manage-provider.html" class="btn cancel-btn me-3">Back</a>
                            <a href="manage-provider.html" class="btn save-btn px-4">Save</a>
                        </div>
                    </div>
                </div>
            </form>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 14, 2022 03:09 AM
pandeygolu4200 says:
@model ThomosMason.Web.Models.Provider.ManageProviderModel

In order to validate you need to modify the Model in the View so that the validation will work for the model.

Refer below example.

Model

public class CustomerModel
{
    public Basic Basic { get; set; }
    public Detail Detail { get; set; }

    public int ActiveIndex { get; set; }
}

public class Basic
{
    [Required(ErrorMessage = "Name is Required")]
    public string Name { get; set; }
}

public class Detail
{
    [Required(ErrorMessage = "Country is Required")]
    public string Country { get; set; }

    [Required(ErrorMessage = "DOB is Required")]
    [DataType(DataType.Date, ErrorMessage = "DOB is Required")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime? DOB { get; set; }
}

Controller

public IActionResult Index()
{
    CustomerModel model = new CustomerModel();
    model.ActiveIndex = 1;
    return View(model);
}

[HttpPost]
public IActionResult Index(CustomerModel model)
{
    if (ModelState.IsValid)
    {
        model.ActiveIndex = 2;
        return View("Index", model);
    }
    else
    {
        return View(model);
    }
}

View

@model Multiple_Model_Submit_MVC_Core.Models.CustomerModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-transparent py-4 px-4">
        <div class="d-flex align-items-center">
            <i class="fas fa-align-left primary-text fs-4 me-3" id="menu-toggle"></i>
            <h2 class="fs-4 m-0">Add Provider</h2>
        </div>
    </nav>
    <div class="master-tab-wrapper provider-wrapper">
        <div class="container-fluid px-4">
            <div class="stepper-wrapper">
                <div class="card p-3 mb-3">
                    <ul class="nav nav-tabs mt-3" data-bs-tabs="tabs" id="myTab">
                        <li class="nav-item me-2">
                            <a class="nav-link active" aria-current="true" data-bs-toggle="tab" href="#step1">
                                Step 1
                                <h6>Personal Details</h6>
                            </a>
                            @Html.ValidationMessage("CustomError", new { @class = "text-danger" })
                        </li>
                        <li class="nav-item me-2">
                            <a class="nav-link" data-bs-toggle="tab" href="#step2">
                                Step 2
                                <h6>License, Certifications & More</h6>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" data-bs-toggle="tab" href="#step3">
                                Step 3
                                <h6>Primary/Sub Specialities</h6>
                            </a>
                        </li>
                    </ul>
                    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index" class="tab-content mt-3">
                        <div class="tab-pane active" id="step1">
                            <div class="provider-details-wrapper">
                                <h6>Personal Details</h6>
                                <div class="row">
                                    <div class="col-lg-3 col-md-4">
                                        <div class="form-group">
                                            <label for="Name">Name</label>
                                            @Html.TextBoxFor(c => c.Basic.Name, new { @class = "form-control", id = "txtName", placeholder = "Enter Name" })
                                            <span asp-validation-for="Basic.Name" class="text-danger"></span>
                                        </div>
                                    </div>
                                    <div class="col-lg-3 col-md-4">
                                        <div class="form-group">
                                            <label for="Country">Country</label>
                                            @Html.TextBoxFor(c => c.Detail.Country, new { @class = "form-control", id = "txtCountry", placeholder = "Enter Country" })
                                            <span asp-validation-for="Detail.Country" class="text-danger"></span>
                                        </div>
                                    </div>
                                    <div class="col-lg-3 col-md-4">
                                        <div class="form-group">
                                            <label for="DOB">DOB</label>
                                            @Html.TextBoxFor(c => c.Detail.DOB, "{0:yyyy-MM-dd}", new { id = "txtDOB", type = "date", @class = "form-control" })
                                            <span asp-validation-for="Detail.DOB" class="text-danger"></span>
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-end mt-5">
                                        <a href="manage-provider.html" class="btn cancel-btn me-3">Back</a>
                                        <input type="submit" class="btn add-btn" value="Save & next" id="btnSaveNext">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="tab-pane" id="step2">
                            <div class="provider-details-wrapper">
                                <h6>License, Certifications & Documents</h6>
                                <div class="row">
                                    <div class="col-lg-3 col-md-4">
                                        <div class="form-group">
                                            <label for="firstname">Document Name</label>
                                            <input type="text" class="form-control" id="firstname">
                                        </div>
                                    </div>
                                    <div class="col-lg-3 col-md-4">
                                        <label for="state">State</label>
                                        <div class="form-group">
                                            <select class="form-control form-select">
                                                <option>Noida</option>
                                                <option value="1"></option>
                                                <option value="2"></option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-lg-3 col-md-4">
                                        <div class="form-group">
                                            <label for="isuuedate">Isuue Date</label>
                                            <input type="date" class="form-control" id="isuuedate">
                                        </div>
                                    </div>
                                    <div class="col-lg-3 col-md-4">
                                        <div class="form-group">
                                            <label for="tax">Expiration Date</label>
                                            <input type="date" class="form-control" id="tax">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-xl-12 col-lg-12 col-md-12 mt-3">
                                        <button class="btn disabled-btn me-3 mb-2">
                                            Drag file here, or Click to Upload
                                        </button>
                                        <button class="btn upload-btn px-5">Upload</button>
                                    </div>
                                </div>                                
                                <div class="d-flex justify-content-end mt-5">
                                    <a href="manage-provider.html" class="btn cancel-btn me-3">Back</a>
                                    <a href="manage-provider.html" class="btn save-btn">Save & next</a>
                                </div>
                            </div>
                        </div>
                        <div class="tab-pane" id="step3">
                            <div class="provider-details-wrapper">
                                <h6>Primary/Sub Specialities Details</h6>
                                <div class="d-flex justify-content-end mt-5">
                                    <a href="manage-provider.html" class="btn cancel-btn me-3">Back</a>
                                    <a href="manage-provider.html" class="btn save-btn px-4">Save</a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="position-fixed top-0 end-0 p-3" style="z-index: 11;display:none;">
        <div id="liveToastdelete" class="toast hide " role="alert" aria-live="assertive" aria-atomic="true"
             data-bs-animation="true" data-bs-autohide="true">
            <div class="toast-header bg-white">
                <strong class="me-auto text-dark">Provider has been Added Succesfully.</strong>
                <small class="text-dark"></small>
                <button type="button" class="btn-close" id="closebtn" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            $('#myTab li:nth-child('+@Model.ActiveIndex+') a').tab('show');
        });
    </script>
</body>
</html>

Screenshot