Click here to Skip to main content
15,894,955 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more: , +
I am creating a regitration form but i do not know why it is returning error
This is my model for form

C#
public partial class ApplicationFormFarmersSolarPower
    {
        public int Id { get; set; }
        public string UniqueId { get; set; }

        //[Required(ErrorMessage = "Please select District.")]
        //public string District { get; set; }

        //[Required(ErrorMessage = "Please select Tehsil.")]
        //public string Tehsil { get; set; }

        //[Required(ErrorMessage = "Please select SubTehsil.")]
        //public string SubTehsil { get; set; }
        public string DistrictName { get; set; }
        public string TehsilName { get; set; }
        public string SubTehsilName { get; set; }

        public string Village { get; set; }

        [StringLength(20, MinimumLength = 1, ErrorMessage = "Please enter a Name within 1 to 20 chars.")]
        [Required(ErrorMessage = "Please Enter Name")]
        [Display(Name = "*Name of Applicant")]
        public string NameOfApplicant { get; set; }

        [StringLength(30)]
        [Required(ErrorMessage = "Please Enter Name of Land Owner")]
        [Display(Name = "*Name of Land Owners / Owners")]
        public string NameOfLandOwners { get; set; }

        [StringLength(30)]
        [Display(Name = "*Address")]
        [Required(ErrorMessage = "Please Enter Registered Address")]
        [RegularExpression(@"[^<->!*]+$", ErrorMessage = "Such Chars (<,!,>,*) are not allowed")]
        public string ResidentAddress { get; set; }

        [StringLength(6, ErrorMessage = "Should not be more than 6 chars.")]
        [Required(ErrorMessage = "Please enter pincode")]
        [RegularExpression(@"^[0-9]+$", ErrorMessage = "Invalid zipcode")]
        public Nullable<long> PinCode { get; set; }

        [StringLength(10, ErrorMessage = "Should not be more than 10 characters.")]
        [Required(ErrorMessage = "Please enter mobile number.")]
        //[RegularExpression(@"/[1-9]{1}\d{9}/", ErrorMessage = "Invalid mobile number.")]
        [Display(Name = "Mobile Number")]
        public Nullable<long> MobileNumber { get; set; }

        [Required(ErrorMessage = "Please enter email id.")]
        [StringLength(100, ErrorMessage = "Should not be more than 100 chars.")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Invalid email address")]
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid email address")]
        [Display(Name = "Email Id")]
        public string EmailId { get; set; }

        [Required(ErrorMessage = "Please select Nearest Station.")]
        [Display(Name = "*Nearest 66 KVA PSPCL Sub Station")]
        public string NearestStation { get; set; }

        [Display(Name = "*Distance of Substation (in meters)")]
        [Required(ErrorMessage = "Please select Distance of Substation.")]
        public string DistanceOfSubstation { get; set; }

        [Display(Name = "Area of Land")]
        [Required(ErrorMessage = "Please select Area of Land")]
        public string AreaOfLand { get; set; }
        public string ProposedPlantCapacity { get; set; }

        [Required(ErrorMessage = "Please select District.")]
        public Nullable<int> DistrictId { get; set; }

        [Required(ErrorMessage = "Please select Tehsil.")]
        public Nullable<int> TehsilId { get; set; }

        [Required(ErrorMessage = "Please select SubTehsil.")]
        public Nullable<int> SubTehsilId { get; set; }
    }

My Home Controller

C#
public ActionResult Index1()
        {
            List<District> allDistrict = new List<District>();
            List<Tehsil> allTehsil = new List<Tehsil>();
            List<SubTehsil> allSubTehsil = new List<SubTehsil>();

            using (FarmerBDContext db = new FarmerBDContext())
            {
                allDistrict = db.Districts.ToList();
            }
            ViewBag.DistrictId = new SelectList(allDistrict, "DistrictId", "DistrictName");
            ViewBag.TehsilId = new SelectList(allTehsil, "TehsilId", "Tehsilname");
            ViewBag.SubTehsilId = new SelectList(allSubTehsil, "SubTehsilId", "SubTehsilName");

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Details(ApplicationFormFarmersSolarPower app)
        {
            List<District> allDistrict = new List<District>();
            List<Tehsil> allTehsil = new List<Tehsil>();
            List<SubTehsil> allSubTehsil = new List<SubTehsil>();

            using (FarmerBDContext db = new FarmerBDContext())
            {
                allDistrict = db.Districts.ToList();
                if (app != null && app.DistrictId > 0)
                { 
                    allTehsil = db.Tehsils.Where(x => x.TehsilId.Equals(app.DistrictId)).OrderBy(a => a.TehsilName).ToList();
                }
                if (app != null && app.TehsilId > 0)
                {
                    allSubTehsil = db.SubTehsils.Where(x => x.SubTehsilId.Equals(app.TehsilId)).OrderBy(a => a.SubTehsilName).ToList();
                }
            }

            ViewBag.DistrictId = new SelectList(allDistrict, "DistrictId", "DistrictName", app.DistrictId);
            ViewBag.TehsilId = new SelectList(allTehsil, "TehsilId", "Tehsilname", app.TehsilId);
            ViewBag.SubTehsilId = new SelectList(allSubTehsil, "SubTehsilId", "SubTehsilName", app.SubTehsilId);

            if (ModelState.IsValid)
            {
                using (FarmerBDContext db = new FarmerBDContext())
                {
                    db.ApplicationFormFarmersSolarPowers.Add(app);
                    db.SaveChanges();
                    ModelState.Clear();
                    app = null;
                    ViewBag.Message = "SuccessFul";
                }
            }
            else
            {
                ViewBag.Message = "UnSuccessFul";
            }

            return View(app);
        }

        [HttpGet]
        public JsonResult GetTehsil(string districtID = "")
        {
            List<Tehsil> allTehsil = new List<Tehsil>();
            int ID = 0;
            if (int.TryParse(districtID, out ID))
            {
                using (FarmerBDContext db = new FarmerBDContext())
                {
                    allTehsil = db.Tehsils.Where(a => a.DistrictId.Equals(ID)).OrderBy(a => a.TehsilName).ToList();
                }
            }

            if (Request.IsAjaxRequest())
            {
                return new JsonResult
                {
                    Data = allTehsil,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                return new JsonResult
                {
                    Data = "Not Valid request",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }

        [HttpGet]
        public JsonResult GetSubTehsil(string tehsilId = "")
        {
            List<SubTehsil> allSubTehsil = new List<SubTehsil>();
            int ID = 0;
            if (int.TryParse(tehsilId, out ID))
            {
                using (FarmerBDContext db = new FarmerBDContext())
                {
                    allSubTehsil = db.SubTehsils.Where(a => a.TehsilId.Equals(ID)).OrderBy(a => a.SubTehsilName).ToList();
                }
            }

            if (Request.IsAjaxRequest())
            {
                return new JsonResult
                {
                    Data = allSubTehsil,
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                return new JsonResult
                {
                    Data = "Not Valid request",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }


My IndexView

HTML
@model LastTry.Models.ApplicationFormFarmersSolarPower

@{
    ViewBag.Title = "Ind1ex";
    Layout = "~/Views/Shared/_LayoutFarmer.cshtml";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<h2>Ind1ex</h2>

@using (Html.BeginForm("Details", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>ApplicationFormFarmersSolarPower</legend>
        @if (ViewBag.Message != null)
        {
            <div style="border:1px solid black">
                @ViewBag.Message
            </div>
        }

        <div class="editor-label">
            @Html.LabelFor(model => model.UniqueId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UniqueId)
            @Html.ValidationMessageFor(model => model.UniqueId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Village)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Village)
            @Html.ValidationMessageFor(model => model.Village)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NameOfApplicant)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NameOfApplicant)
            @Html.ValidationMessageFor(model => model.NameOfApplicant)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NameOfLandOwners)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NameOfLandOwners)
            @Html.ValidationMessageFor(model => model.NameOfLandOwners)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ResidentAddress)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ResidentAddress)
            @Html.ValidationMessageFor(model => model.ResidentAddress)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PinCode)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PinCode)
            @Html.ValidationMessageFor(model => model.PinCode)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.MobileNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.MobileNumber)
            @Html.ValidationMessageFor(model => model.MobileNumber)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EmailId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmailId)
            @Html.ValidationMessageFor(model => model.EmailId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NearestStation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NearestStation)
            @Html.ValidationMessageFor(model => model.NearestStation)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DistanceOfSubstation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DistanceOfSubstation)
            @Html.ValidationMessageFor(model => model.DistanceOfSubstation)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.AreaOfLand)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.AreaOfLand)
            @Html.ValidationMessageFor(model => model.AreaOfLand)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProposedPlantCapacity)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProposedPlantCapacity)
            @Html.ValidationMessageFor(model => model.ProposedPlantCapacity)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DistrictName)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.DistrictName, @ViewBag.DistrictId as SelectList, "Select District", new { @class = "ddl" })
            @Html.ValidationMessageFor(model => model.DistrictId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.TehsilName)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.TehsilName, @ViewBag.TehsilId as SelectList, "Select Tehsil", new { @class = "ddl" })
            @Html.ValidationMessageFor(model => model.TehsilId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.SubTehsilName)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.SubTehsilName, @ViewBag.SubTehsilId as SelectList, "Select SubTehsil", new { @class = "ddl" })
            @Html.ValidationMessageFor(model => model.SubTehsilId)
        </div>

        <p>
            <input type="submit" value="Details" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@*@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")*@


<script type="text/javascript">
    //$(document).ready(function () {

    $(document).ready(function () {
        $("#DistrictName").change(function () {

            var dId = parseInt($("#DistrictName").val());
            
            if (!isNaN(dId)) {
                var ddState = $("#TeshilName");
                ddState.empty();
                ddState.append($("<option></option").val("").html("Select State"));
                $.ajax({
                    url: "@Url.Action("GetTehsil", "Home")",
                    type: "GET",
                    data: { "districtID": dId },
                    dataType: "json",
                    success: function (data) {
                        $.each(data, function (i, val) {
                            ddState.append(
                                    $("<option></option>").val(val.TehsilId).html(val.TehsilName)
                                );
                        });
                    },
                    error: function () {
                        alert("Error!");
                    }
                });
            }
        });

        $("#TehsilName").change(function () {
            var tehsilID = parseInt($('#TehsilName').val());
            if (!isNaN(tehsilID)) {
                var ddstate = $("#SubTeshilName");
                ddstate.empty();
                ddstate.append($("<option></option>").val("").html("Select SubTehsil"));

                $.ajax({
                    url: "@Url.Action("GetSubTehsil","Home")",
                    type: "GET",
                    data: { "tehsilId": tehsilID },
                    dataType: "json",
                    success: function (data) {
                        $.each(data, function (i, val) {
                            ddstate.append(
                                    $("<option></option>").val(val.SubTehsilId).html(val.SubTehsilName)
                                );
                        });
                    },

                    error: function (data) {
                        alert("Error!");
                    }
                });
            }
        });
    });

</script>


When i run it in Debug Mode it is returning the value from GetTehsil action in Home Controller, i even alerted the selected value which is coming fine but i do not know why it is giving error any idea?

My three classes for DropDownList, these classes are generated by Entity framework
C#
public partial class District
    {
        public District()
        {
            this.tbTehsils = new HashSet<Tehsil>();
        }
    
        public int DistrictId { get; set; }
        public string DistrictName { get; set; }
    
        public virtual ICollection<Tehsil> tbTehsils { get; set; }
    }

public partial class Tehsil
    {
        public Tehsil()
        {
            this.tbSubTehsils = new HashSet<SubTehsil>();
        }
    
        public int TehsilId { get; set; }
        public string TehsilName { get; set; }
        public int DistrictId { get; set; }
    
        public virtual District tbDistrict { get; set; }
        public virtual ICollection<SubTehsil> tbSubTehsils { get; set; }
    }

public partial class SubTehsil
    {
        public int SubTehsilId { get; set; }
        public string SubTehsilName { get; set; }
        public Nullable<int> TehsilId { get; set; }
    
        public virtual Tehsil tbTehsil { get; set; }
    }
Posted
Updated 19-Jul-15 23:16pm
v2
Comments
Wendelius 20-Jul-15 5:19am    
What is the error you get?
lokopi.nagar 20-Jul-15 5:24am    
This error whuch is on error state in ajax
error: function (data) {
alert("Error!");
}
F-ES Sitecore 20-Jul-15 5:29am    
Use the network section of the browser's dev tools (f12), or something like Fiddler, to examine the network traffic and see if you can find the actual error.
lokopi.nagar 20-Jul-15 5:38am    
This is what fiddler provide
Host: localhost:60160
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36
Referer: http://localhost:60160/home/index1
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,da;q=0.6
Cookie: __RequestVerificationToken=wRq_g_M_YXwjpQQGtIXekS78hGAjd1OWaFoYi7buXX5KhwpXKvF3wirO68R3pjixObB7HYpH53aEORnYZVHk0qTNz6cjMU2SR3-zF1irEuE1
F-ES Sitecore 20-Jul-15 5:41am    
You need to look at the response html, that will probably contain an error page of sorts.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900