Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, everyone. I am working on a c# mvc application. I validate a string property as Required in a ViewModel. Here is my code from the ViewModel:

[Required (ErrorMessage = "Please enter a number.")]
[RegularExpression("^[0-9]*$", ErrorMessage = "Please enter only a number not another sign.")]
public string BoardNumber { get; set; }

Here is the code from the View:

<table style="background-color:rgba(224, 95, 3, 0.18);border-radius:8px;" align="center">
        <tr>
            <td>
                "margin-left: 20px">BoardNumber:
                <p style="margin-left: 20px; margin-right:20px;">
                    @Html.TextBoxFor(x => x.BoardNumber, new { @class = "form-control" , @Value = "" }) <br />
                    @Html.ValidationMessageFor(x => x.BoardNumber, "", new { @class = "bg-warning" })
                    @Html.ValidationMessage("error", "", new { @class = "bg-warning" })
                </p>
            </td>
            <td>
                <p>
                    <input type="submit" style="margin-left: 20px; margin-right:20px; margin-top: 10px;" value="Submit" class="btn btn-primary orders-search-button">
                </p>
            </td>
        </tr>
    </table>


The problem is that when I go to the view, the required error message is shown even though I haven't pressed submit, and I want it to be displayed only if I press Submit and haven't entered anything. How should I fix that?

What I have tried:

I haven't tried anything because I don't know what to do.
Posted
Updated 1-Oct-18 2:48am

1 solution

add two different methods for viewing and posting form like this

public ActionResult CreateSomething()
{
return view();
}

[HttpPost]
public ActionResult CreateSomething(Models.ModelName ModelName)
{

}
 
Share this answer
 
Comments
Member 13992723 1-Oct-18 8:58am    
I have get and post methods for the veiw already.
Member 13992723 1-Oct-18 9:14am    
Your answer helped me to find the problem. The problem is that in my get method I have the ViewModel as a parameter and that's why I get the error message without pressing the submit button. I removed the ViewModel from the parameter list and everything works fine. Thanks for the answer.
summiya1 1-Oct-18 9:16am    
Great Happy Coding :)

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