开发者

ASP.NET MVC Validation Issues when prefilling Model

I am having issues on a page with a validation message for my model.

The page has a form for a search, and the model is an object that represents the items in the form. When the user visits the page, the zip code is automatically filled in the controller and then the model is passed into the view.

This causes the validation message for the zip code field to show, even though the zip code is in proper format.

Here is the code in the controller:

public ActionResult WhereToBuyIndex(LocatorSearch searchOptions)
{
    if (searchOptions == null)
    {
        searchOptions = new LocatorSearch();
    }

    //ATTEMPT TO GET USER ZIP CODE
    AppLib.Geolocation.Web.WebGeolocationService geoService = new AppLib.Geolocation.Web.WebGeolocationService();
    searchOptions.Address = geoService.GeolocateToZi开发者_运维百科pCode(Request.ServerVariables["REMOTE_ADDR"]);
    if (searchOptions.Address == "00000") { searchOptions.Address = "90210"; }

    ViewBag.Countries = LocatorService.Instance.LoadCountriesWithCustomers();

    return View("Index", searchOptions);
}

and the only lines in the view that involve the zip field are as follows:

@Html.TextBoxFor(model => model.Address, new { id = "fAddress" })
<span class="failure">@Html.ValidationMessageFor(model => model.Address)</span> 

if I try to prefill any other fields, I get the same validation problem -- all of the prefilled field error messages are shown

Any help is greatly appreciated,

Thank you.


When you use this method signature, the default binder for LocatorSearch performs validation before any code in the function is called:

public ActionResult WhereToBuyIndex(LocatorSearch searchOptions)

There are a few ways around the error, one being to use the [HttpPost] attribute on this function and use one with no arguments for when the user hasn't submitted a search yet to populate the default values.

Alternately, you could clear the error using ModelState["Address"].Errors.Clear(); That is a bit of an uglier solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜