Monday, 30 March 2020

Create Page Model attached MVC C#

This post lets you understand to create a view which bind with model, using this approach you can create to form to save the record in the database fastest and easily. As we know validation and binding model with jquery is very time taking task. The model view automatically creates forms as per the model. You can make validation rules in the model.


Model


Note : use (using System.ComponentModel.DataAnnotations;) namespace 

   public class ApplyOnlineModel : CommonDataModel
    {
        [Required (ErrorMessage="Please enter your name")]
        [Display(Name="Student Name")]
        public string StudentName { get; set; }
        [Required (ErrorMessage="First Phone number"),Display (Name="working Phone number")]
        [RegularExpression(@"^([0-9]{10})$", ErrorMessage = "Invalid Mobile Number.")]
        public string Phone1  { get; set; }
        [Display (Name="Alternate Phone Number")]
    }

View


Note : Add the following reference 

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using(Html.BeginForm())
 {
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true)
                   
                    @Html.LabelFor(model => model.StudentName  )                   
                    @Html.TextBoxFor(model => model.StudentName, new { @class = "form-control", placeholder = "Your Name" })
                    @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "g-mandate" })<br />
                   
                    @Html.LabelFor(model => model.Phone1  )                   
                    @Html.TextBoxFor(model => model.Phone1, new { @class = "form-control"  })
                    @Html.ValidationMessageFor(model => model.Phone1, "", new { @class = "g-mandate" })<br />
                   
                    
                    @Html.LabelFor(model => model.Phone2  )                   
                    @Html.TextBoxFor(model => model.Phone2, new { @class = "form-control" })<br />
              <input type="submit" value="Save" class="btn btn-danger" />        
                   
}

Controller 


  [HttpPost]
        public ActionResult apply(FormCollection data)
        {
            string ErrMsg = "";
            ApplyOnlineModel ob = new ApplyOnlineModel();
            WebsiteRepository ob2 = new WebsiteRepository();
             if (ModelState.IsValid)
            {               
                ob.StudentName = data["StudentName"];
                ob.Phone1 = data["Phone1"];
                ob.Phone2 = data["Phone2"];            
                ob2.SaveApplyOnline(ob, ref ErrMsg);
                if (ErrMsg == "")
                    return RedirectToAction("success", "common");
                else
                    return RedirectToAction("error", "Common", new { msg = @ErrMsg });
               
            }
             return RedirectToAction("error","common");
        }


Repository



public bool SaveApplyOnline(ApplyOnlineModel ob, ref string ErrMsg)
        {
            String result = "";
            try
            {
                using (SqlConnection dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ToString()))
                {
                    using (SqlCommand cmd = new SqlCommand("[dbo].[AddApplyOnline]", dbcon))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.AddWithValue("@StudentName", ob.StudentName);
                        cmd.Parameters.AddWithValue("@Phone1", ob.Phone1);
                        cmd.Parameters.AddWithValue("@Phone2", ob.Phone2);

                        if (dbcon.State == ConnectionState.Closed)
                            dbcon.Open();
                        cmd.ExecuteNonQuery();
                        result = "1";
                    }
                }
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
            }
            if (result == "1")
                return true;
            else
                return false;
        }

No comments:

Post a Comment