Question

I have the following two properties in Country class (Model).

public class Country
{
        [HiddenInput(DisplayValue = false)]
        public int Id { get; set; }

        [Required]
        [Remote("CheckName", "Country", AdditionalFields = "Id")]
        public string Name { get; set; }
}

Above I am expecting Id to be passed to CheckName method. I have the CheckName method in CountryController as:

public JsonResult CheckCountryName(string Name, int Id = 0)
{
     return Json(!repository.Countries.Where(c => c.Id != Id).Any(c => c.Name == Name), JsonRequestBehavior.AllowGet);
}

I am using editor template for Country class, @Html.EditorFor(m => m.Country)

Id property is being rendered as hidden field by id as Country_Id and name as Country.Id. When I am editing Name field, CheckName is not getting the required values (name gets null and Id gets 0 (being the default value))

I checked in Fiddler, request is going to server as GET /Country/CheckName?Country.Name=abc&Country.Id=0 HTTP/1.1.

What should I do to resolve this ?

Was it helpful?

Solution 2

I changed my method and used Bind attribute and it works now.

public JsonResult CheckCountryName([Bind(Prefix="Country")]Country oCountry)
{
     return Json(!repository.Countries.Where(c => c.Id != oCountry.Id).Any(c => c.Name == oCountry.Name), JsonRequestBehavior.AllowGet);
}

OTHER TIPS

It's passing your model through. So your JsonResult should be using your model, Country, not Name and Id individually.

Like this:

public JsonResult CheckCountryName(Country country)
{
     return Json(!repository.Countries.Where(c => c.Id != country.Id)
                 .Any(c => c.Name == country.Name), 
                 JsonRequestBehavior.AllowGet);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top