How to populate a form value from a drop-down?

2019-08-09 07:34发布

Follow-on from this question: If I want to calculate a value based on a user's selection from a drop down list, and put that value into a form variable/model property, how do I do that?

2条回答
做个烂人
2楼-- · 2019-08-09 07:51

I guess (info from the previous question) you want to get the Item Price data using ajax based on the selected Item in the dropdown and send that to your action method as part of the normal form post.

Step1) Create the ViewModel for Product.

public class ProductViewModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
    public decimal ItemPrice { set; get; }
}

Step2) Create a Product Controller like this

public class ProductController : Controller
{
    public ActionResult Index()
    {
        var objProduct = new ProductViewModel();
        objProduct.Items = new[]
        {
            new SelectListItem { Value = "1", Text = "Perfume" },
            new SelectListItem { Value = "3", Text = "Shoe" },
            new SelectListItem { Value = "3", Text = "Shirt" }
        };
        return View(objProduct);
    }
    [HttpPost]
    public ActionResult Index(ProductViewModel objProduct)
    {
        //Validate and Save to DB and do whatever            
        return View(objProduct);
    }
    public string GetPrice(int itemId)
    {
        decimal itemPrice = 0.0M;
        //using the Id, get the price of the product from your data layer and set that to itemPrice variable.
        itemPrice = 23.57M;
        return itemPrice.ToString();
    }
}

Step 3) Add the Strongly typed View

@model MvcApplication1.Models.ProductViewModel
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

@using (Html.BeginForm())
{    
    @Html.DropDownListFor(x => x.SelectedItemId, Model.Items, "Select..")
    <div id="divItemPrice"> </div>
     @Html.HiddenFor(x=>x.ItemPrice)       
    <button type="submit">Save</button>
}
<script type="text/javascript">
$(function(){
  $("#SelectedItemId").change(function(){
    var val=$(this).val();  
    console.debug(val);    
    $.get("@Url.Action("GetPrice","Product")",  { itemId : val },function(data){
      $("#ItemPrice").val(data);
      $("#divItemPrice").html(data);
    });     
  });
});
</script>

When you change the selected item in the drop down, using jQuery ajax, it will make a call to GetPrice Action method and get the data. Show it in the div and set as the Value of HiddenField for ItemPrice.

enter image description here and When you post the Form, You will have it present in the ViewModel posted. enter image description here

Hope this helps.

查看更多
Luminary・发光体
3楼-- · 2019-08-09 07:52

Really, if I had a single advice to give any ASP.NET MVC developer that would be: use a view model and forget about ViewBag/ViewData. In 99% of the cases that is the solution to his questions/problems.

So here's the minimal view model that will allow you to properly represent a dropdown list:

public class MyViewModel
{
    // a scalar property on the view model to hold the selected value
    [DisplayName("item")]
    [Required]
    public string ItemId { get; set; }

    // a collection to represent the list of available options
    // in the drop down
    public IEnumerable<SelectListItem> Items { get; set; }

    ... and some other properties that your view might require
}

then have a controller action that will populate and pass this view model to the view:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        // TODO: those values probably come from your database or something
        Items = new[]
        {
            new SelectListItem { Value = "1", Text = "item 1" },
            new SelectListItem { Value = "2", Text = "item 2" },
            new SelectListItem { Value = "3", Text = "item 3" },
        }
    };
    return View(model);
}

then you could have a corresponding strongly typed view to this view model that could contain a form and the dropdown list:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.ItemId)
    @Html.DropDownListFor(x => x.ItemId, Model.Items, "--Select One--")
    <button type="submit">OK</button>
}

and finally you could have a corresponding action on your controller to which this form will be submitted and inside which you will be able to retrieve the selected value from the dropdown list:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    // model.ItemId will contain the selected value from the dropdown list
    ...
}
查看更多
登录 后发表回答