Display Server Side Model Validation Error message in View in ASP.Net MVC

Last Reply 6 months ago By dharmendr

Posted 6 months ago

 I want that the user should not enter more than 4 places of decimal value in the field and i want it to be server side validation. But the error is not coming when i am trying to validate it.

    public class LandDetailController : Controller
    {
        
        // GET: LandDetail
        public ActionResult Index()
        {
            CPSE_Landdetails cs = new CPSE_Landdetails();
            cs.PsuList = GetPsu();
            return View(cs);
        }

        [HttpPost]
        public ActionResult Index(CPSE_Landdetails cs)
        {
            if(!string.IsNullOrEmpty(cs.LandFreeHold))
            {
                string landfree = @"^[0-9]+(\.[0-9]{1,2})$";
                Regex re = new Regex(landfree);
                if (!re.IsMatch(cs.LandFreeHold))
                {
                    ModelState.AddModelError("LandFreeHold","Land Entry Not Valid");
                }
            }

            return View();
        }

        private List<SelectListItem> GetPsu()
        {
            string userid = Session["UserID"].ToString();
            string str = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
            List<SelectListItem> List = new List<SelectListItem>();
            using (SqlConnection con = new SqlConnection(str))
            {
                string query = "select Section_PSU from [CPSEdb].[dbo].[SectionMaster1] where [Section_name]='"+userid.ToString()+"'";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader rd = cmd.ExecuteReader())
                    {
                        while (rd.Read())
                        {
                            List.Add(new SelectListItem
                            {
                                Text = rd["Section_PSU"].ToString(),
                                Value = rd["Section_PSU"].ToString()

                            });
                        }
                    }
                    con.Close();
                }
            }
            return List;
        }
    }

 

<div class="container" style="margin-top:20px">
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        if (!@ViewData.ModelState.IsValid)
        {
            <span class="field-validation-error">@ViewData.ModelState["LandFreeHold"].Errors[0].ErrorMessage</span>
        }
        <div class="card">
            <div class="card-header">
                <table width="1024">
                    <tr>
                        <td valign="bottom"><label>Choose PSU</label></td>
                        <td>
                            @Html.DropDownListFor(model => model.CPSE_id, Model.PsuList, "-- Choose PSU --", new { @class = "form-control", required = "required" })
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div class="card" style="margin-top:20px">
            <div class="card-header alert-danger">
                <label>Land Details</label>
            </div>
            <div class="card-body">
                <table width="1024">                    
                    <tr>
                        <td valign="bottom">
                            <label>Land Free Hold Other</label>
                        </td>
                        <td>
                            @Html.TextBoxFor(model => model.LandFreeHole_Other, new { @class = "form-control", required = "required" })
                        </td>
                        <td valign="bottom">
                            <label style="margin-left:30px">Land Free Hold Unit</label>
                        </td>
                        <td>
                            @Html.TextBoxFor(model => model.LandFreeHold_unit, new { @class = "form-control", required = "required" })
                        </td>
                    </tr>                    
                </table>
            </div>
        </div>
        <div style="text-align:center;margin-top:20px">
            <input type="submit" value="Submit Information" class="btn btn-primary" />
        </div>
    }

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
</div>

 

Posted 6 months ago Modified on 6 months ago

Hi sunnyk21,

Check this example. Now please take its reference and correct your code.

Model

public class CustomerModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Salary { get; set; }
    public List<SelectListItem> PsuList { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        CustomerModel model = new CustomerModel();
        model.PsuList = GetPsu();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(CustomerModel cs)
    {
        if (!string.IsNullOrEmpty(cs.Salary))
        {
            string landfree = @"^[0-9]+(\.[0-9]{1,4})$";
            Regex re = new Regex(landfree);
            if (!re.IsMatch(cs.Salary))
            {
                ModelState.AddModelError("LandFreeHold", "Land Entry Not Valid");
            }
        }
        cs.PsuList = GetPsu();
        return View(cs);

    }

    private List<SelectListItem> GetPsu()
    {
        List<SelectListItem> List = new List<SelectListItem>();
        List.Add(new SelectListItem { Text = "A", Value = "1" });
        List.Add(new SelectListItem { Text = "B", Value = "2" });
        List.Add(new SelectListItem { Text = "C", Value = "3" });
        return List;
    }
}

View

<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <style type="text/css">
        .field-validation-error
        {
            color: #e80c4d;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <% using (Html.BeginForm("Index", "Home", FormMethod.Post))
       {%>
    Choose PSU:
    <br />
    <%:Html.DropDownListFor(model => model.PsuList, Model.PsuList, "-- Choose PSU --",new { @class = "form-control", required = "required" })%>
    <br /><%:Html.TextBoxFor(model => model.Salary, new { @class = "form-control", required = "required"  })%>
    <%if (!ViewData.ModelState.IsValid)
      { %>
    <span class="field-validation-error"><%:Html.ValidationMessage("LandFreeHold")%></span>
    <%} %>
    <br /><input type="submit" value="Submit Information" class="btn btn-primary" />
    <% } %>
</body>
</html>

Screenshot