ASP.Net MVC Error Validation

I have an error validation issue with an int.

I have validation for a customer name:

if (String.IsNullOrEmpty(CustomerName))
            yield return new RuleViolation("Customer Name Required", "CustomerName");

now if I want to add validation for a city, in this case I have a CityID that gets saved as type int, so I can't write my if statement the same way...because there's no int.IsNullOrEmpty method. Let's say the user didn't select the dropdown for city - it's basically saving with no value.

What's the best way to write my validation statement for an int?

UPDATE:Here's a sample of what I have for my form in my view:

<% using (Html.BeginForm())
   {%>

    <fieldset>
        <legend>Add a new customer</legend>
        <p>
            <label for="CustomerName">Customer Name:</label>
            <%= Html.TextBox("CustomerName")%>
            <%= Html.ValidationMessage("CustomerName", "*")%>
        &nbsp;&nbsp;
            <label for="CityID">City:</label>
            <%= Html.DropDownList("CityID", Model.Cities as SelectList, "Select City")%>
            <%= Html.ValidationMessage("CityID", "*")%>
        &nbsp;&nbsp;
            <input type="submit" value="Create New Customer" />
        </p>
    </fieldset>

<% } %>

and my view model looks like this:

public class CustomerFormViewModel
{
    //Properties
    public Customer Customer { get; set; }
    public SelectList Cities { get; set; }

    //Constructor
    public CustomerFormViewModel(Customer customer)
    {
        CustomerRepository customerRepository = new CustomerRepository();
        Customer = customer;
        Cities = new SelectList(customerRepository.FindAllCities(), "CityID", "CityName");  
    }
}

使用可为空的整数,

int? i = null;

I had this same exact requirement a week ago. You can solve this in two ways.

1) In Dropdown you will always have " Please Select " with default value as -1 . When a form is submitted and no city is selected then MVC model will bind -1 (default value) for CityID. So you can always check if CityID > 0 else "raise error"

2) Use c# 3.0 feature Nullable Int (int?) for CityID which means your CityID can also be null. If no value is passed for CityID, your cityID will always be null.


You can set a default value in the route config. If you set the default to a value you know is invalid then you can just check for that value. If your cities are numbered 1 through X then set the default at -1 and check for that.

链接地址: http://www.djcxy.com/p/30568.html

上一篇: 预填模型时ASP.NET MVC验证问题

下一篇: ASP.Net MVC错误验证