mardi 25 avril 2017

C# checkboxes need to have one item selected, if not then display a message to the users

Morning folks,

I have the following checkbox area on my create.cshtml page in my c# mvc project. I am using visual studio 2015 for my project.

I have a section on my web page that lists three options for the user in the form of checkboxes. The user must select at least one of these items.

This is what code for the checkboxes looks like on my create.cshtml page....

             @Html.CheckBoxFor(model => model.carer.ParentResp, new { id = "rbParent" }))
             @Html.Label("rbParent", "Parental Responsibility")<br />
             @Html.CheckBoxFor(model => model.carer.NextOfKin, new { id = "rbNext" })
             @Html.Label("rbNext", "Next of Kin")<br />
             @Html.CheckBoxFor(model => model.carer.Keyholder, new { id = "rbKey" })
             @Html.Label("rbKey", "Keyholder?")

With the above code i have the following errors for all three items....

  • Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type...
  • Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

In my database the three fields are set at data type bit and in my model within my mvc project, they are brought in using entity framework as data type bool.

I believe that in my controller, i need to check and see if these items are checked or not.

I have added this following code to my controller...

        //Do a check to see if the checkbox have a value
        if (carer.ParentResp.HasValue || carer.NextOfKin.HasValue || carer.Keyholder.HasValue)
        {
            vmPopulateData.carer = carer;
        }
        else 
        {
            ClientScript.RegisterClientScriptBlock(Me.GetType(), "Message", "alert('" + "Please Select all check boxes that apply" + "');", true);
        }

Im simply wanting to check if any of the three check boxes have a value, if not then to display a message to the user.

I have seen many examples use a ClientScript.RegisterClientscriptBlock method, but i cannot get this to work. I get the following error messages...

  • The name 'ClientScript' does not exist in the current context
  • The name 'Me' does not exist in the current context

Am i missing an namespace to register these items?

Im really struggeling to get this functionality working. Any pointers or examples people have used previously would be welcomed. Im not looking to do anything really clever or over engineering anything here. Just looking for a simple validation element to check and see if a user has checked at least one item so the form can be submitted.

Regards Betty




Aucun commentaire:

Enregistrer un commentaire