.NET MVC Updating a View Using a Model Property

I used the approach described in this article to create a drop-down list.

Model

public class IceCreamFlavor
{
    public int Id { get; set; }
    public string Name { get; set; }
}

View model

public class ViewModel
{
    private readonly List<IceCreamFlavor> _flavors;

    [Display(Name = "Favorite Flavor")]
    public int SelectedFlavorId { get; set; }

    public IEnumerable<SelectListItem> FlavorItems
    {
        get { return new SelectList(_flavors, "Id", "Name");}
    }
}

View

@Html.LabelFor(m=>m.SelectedFlavorId)
@Html.DropDownListFor(m => m.SelectedFlavorId, Model.FlavorItems)
@Html.ValidationMessageFor(m=>m.SelectedFlavorId)
<input type="submit" value="Submit" /> 

This approach works great.

Result

Now I want to display the Models property in the same view. As an example, suppose we had the following properties.

public class IceCreamFlavor
{
    public int Id { get; set; }
    public string Name { get; set; }
    public float Price { get; set; }
}

Now under the dropdown I need to display the price as

Price: 15.99

How can i achieve this?

+4
source share
2 answers

To display a property without a model after submitting, you can simply break into HTML to display it:

@if (Model.Price != 0.0F)
{
    <b>Price @Model.Price.ToString("0.00") </b>
}

, ViewModel:

public class ViewModel
{
       private readonly System.Collections.Generic.List<IceCreamFlavor> _flavors;

        public ViewModel()
        {
         // Construct Flavors
        }

        public List<IceCreamFlavor> AllFlavors
        {
            get
            {
                return _flavors;    
            }
        }

        [Display(Name = "Favorite Flavor")]
        public int SelectedFlavorId { get; set; }

        public System.Web.Mvc.SelectList FlavorItems
        {
            get { return new System.Web.Mvc.SelectList(_flavors, "Id", "Name");}
        }
    }

:

@if (Model.AllFlavors.Any(f => f.Id == Model.SelectedFlavorId))
{
<b>Price @Model.AllFlavors.First(f => f.Id == Model.SelectedFlavorId).Price.ToString("0.00") </b>
}

, , Flavor ViewModel ( ). Flavors , JavaScript , .

onchange JavaScript/JQuery , . ( AJAX , ..)


, :

ViewModel:

    public IceCreamFlavor SelectedFlavor
    {
        get 
        {
            return _flavors.FirstOrDefault(f => f.Id == this.SelectedFlavorId);
        }
    }

:

   @if (Model.SelectedFlavor != null)
   {
    <b>Price @Model.SelectedFlavor.Price.ToString("0.00") </b>
   }
0

, ajax .

  • DropDownListFor , - . , : '10.0;12.0;...', JavaScript , .

  • MyDropDownListFor, , , <option>.., html- , . :

, , JavaScript, , .

0

Source: https://habr.com/ru/post/1626694/


All Articles