Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My problem I am binding the data to the Dropdownlist from the database and it works fine up to that point. When i am submitting the form it automatically returning null value and finally ModelState.IsValid is also returning false.

While searching from the internet I have given the code:
var errors = ModelState.Values.SelectMany(x => x.Errors);


I will briefly describe my problem

Please help me to solve this problem

What I have tried:

My Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult EmployeeLeave(EmployeeLeaveViewModel objLeave)
{
    string typeOfLeaveText = Request.Form["HiddenText"].ToString();
    if (string.IsNullOrEmpty(objLeave.HiddenText))
    {
        ModelState.AddModelError("Error", "Leave type cannot be default value");
    }
}

My View:
<div class="form-group">
    @Html.DropDownListFor(m => m.HiddenText, Model.Nature, "-Please Select-")
    @Html.HiddenFor(m => m.HiddenText)
    @Html.ValidationMessageFor(m => m.Nature, "", new { @style = "color:red" })
</div>

My Model:
public string HiddenText { get; set; }

[Required(ErrorMessage = "Type of Leave field is required")]
[Display(Name = "Type of Leave")]
public List<SelectListItem> NatureofLeave { get; set; }
Posted
Updated 4-Aug-17 4:14am
Comments
Thomas Daniels 4-Aug-17 1:27am    
Is that your full view? Where is the code to send it to the Controller? Is it with a 'form' tag and a button? JavaScript?
Member 8583441 4-Aug-17 1:29am    
It is in the form tag and having submit as well.... Further related forms i am having jQuery but not related to the above described problem sir

1 solution

Quote:
@Html.DropDownListFor(m => m.HiddenText, Model.Nature, "-Please Select-")

Your drop-down list is posting to the HiddenText field. It should presumably be posting to the NatureOfLeave field instead:
@Html.DropDownListFor(m => m.NatureOfLeave, Model.Nature, "-Please Select-")


Also, your model seems to be confusing the list of options with the selected option:
// The value selected in the list:
[Required(ErrorMessage = "Type of Leave field is required")]
[Display(Name = "Type of Leave")]
public string NatureOfLeave { get; set; }

// The list of options to pick from:
public List<SelectListItem> Nature { get; set; }
 
Share this answer
 
v2
Comments
Member 8583441 22-Aug-17 6:08am    
Sorry for the late reply..... My project has been completed and having another project ...... And i very much thankful to you @Richard Deeming sir

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