Peter Larsson
Peter Larsson

Reputation: 333

MVC Model loses binding

I have an issue with MVC (new to this, coming from MVVM in WPF).

I have a combobox in my cshtml file that lets the user choose a country from the list. However, in my model when I try to fetch the country from the list the collection is null.

<div class="inputs">
    @Html.LabelFor(model => model.SelectedCountry)
    <div class="input-box">
        @Html.DropDownListFor(model => model.CountryID, Model.AvailableCountries)
    </div>
    @Html.ValidationMessageFor(model => model.SelectedCountry)
</div>

As you can see I bind the selected value to CountryID. In my model I use this CountryID to fetch the name from the list of countries and set the SelectedCountry string to whatever the user has picked.

The problem is when I try to fetch the country from the list in my model the list is null.

The list of countries in my model:

public IList<SelectListItem> AvailableCountries 
{ 
    get
    {
        if (_availableCountries == null)
            _availableCountries = new List<SelectListItem>();
        return _availableCountries;
    }
    set
    {
        _availableCountries = value;
    }
}

And the population of the list of countries in my controller.

foreach (var c in _countryService.GetAllCountries())
{
    model.AvailableCountries.Add(new SelectListItem() { Text = c.Name, Value = c.Id.ToString() });
}

Also as you see in the cshtml, the value is bound to CountryIID and the code for that property is:

public int CountryID
{
    get
    {
        return _countryID;
    }
    set
    {
        if (_countryID != value)
        {
            _countryID = value;
            List<SelectListItem> _list = new List<SelectListItem>(AvailableCountries);
                SelectedCountry = _list.Find(x => x.Value == _countryID.ToString()).Text;
        }
    }
}

/Peter

Upvotes: 0

Views: 460

Answers (2)

Peter Larsson
Peter Larsson

Reputation: 333

Solved the issue by taking care of the CountryId and translating it in my controller instead. Then just repopulating the AvailableCountries list if the model was not valid and send it back to the view.

Upvotes: 0

C M
C M

Reputation: 703

Your binding for dropdownlistfor is not proper.

You are suppose to provide field name whose value will be bind by Razor engine to dropdownlist for that you need to provide the property name that you want to bind in dropdown. Try this out

@Html.DropDownListFor(model => model.ActionId, new SelectList(@Model.AvailableCountries,"AccountID","AccountName"))

where AccountId,AccountName is the property field inside AvailableCountries where AccountName values will be show in page and AccountId will be bind on select.

Hope this helps...

Upvotes: 1

Related Questions