How to update a label from a postback in MVC3/Razo

2020-07-27 19:05发布

MVC/Razor/Javascript newbie question:

I have a MVC3/Razor form where the use can select a single product from a drop down list.

<div class="editor-label">
  Product
</div>
<div class="editor-field">
  @Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
  @Html.ValidationMessageFor(model => model.ProductID)
</div>

What I then want is to display the price of the selected product on a label just below the drop down list (model property name is Amount).

This should be pretty easy, but I am pretty new at Razor, and know almost nothing about Javascript, so I would appreciate any verbose explanations of how do do it, and how it all hangs together.

2条回答
Rolldiameter
2楼-- · 2020-07-27 19:36

The Amount isn't available to your view when the user selects a product (remember the page is rendered on the server, but actually executes on the client; your model isn't available in the page on the client-side). So you would either have to render in a JavaScript array that contains a lookup of the amount based on the product which gets passed down to the client (so it's available via client-side JavaScript), or you would have to make a callback to the server to retrieve this information.

I would use jQuery to do this.

Here's a simple example of what the jQuery/Javascript code might look like if you used an array.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
   $(document).ready(function() {  
       // This code can easily be built up server side as a string, then
       // embedded here using @Html.Raw(Model.NameOfPropertyWithString)
       var list = new Array();
       list[0] = "";
       list[1] = "$1.00";
       list[2] = "$1.25";

       $("#ProductID").change(displayAmount).keypress(displayAmount);

       function displayAmount() {
          var amount = list[($(this).prop('selectedIndex'))];
          $("#amount").html(amount);
       }
    });
</script>
<select id="ProductID" name="ProductID">
  <option value="" selected>-- Select --</option>
  <option value="1">First</option>
  <option value="2">Second</option>
</select>
<div id="amount"></div>

You'll want to spend some time looking at the docs for jQuery. You'll end up using it quite a bit. The code basically "selects" the dropdown and attaches handlers to the change and keypress events. When they fire, it calls the displayAmount function. displayAmount() retrieves the selected index, then grabs the value out of the list. Finally it sets the HTML to the amount retrieved.

Instead of the local array, you could call your controller. You would create an action (method) on your controller that returned the value as a JsonResult. You would do a callback using jquery.ajax(). Do some searching here and the jQuery site, I'm sure you'll find a ton of examples on how to do this.

查看更多
乱世女痞
3楼-- · 2020-07-27 19:44

Add a div/span under the Dropdown .

@Html.DropDownList("ProductID", (IEnumerable<SelectListItem>)ViewBag.Products, "--Select One--")
<div id="itemPrice"></div>

and in your Script, make an ajax call to one of your controller action where you return the price.

$(function(){
  $("#ProductId").change(function(){
    var val=$(this).val();        
    $("#itemPrice").load("@Url.Action("GetPrice","Product")", { itemId : val });
  });
});

and have a controller action like this in your Product controller

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.

  return itemPrice.ToString();
}

That is it ! Make sure you have jQuery loaded in your page and this will work fine.

EDIT : Include this line in your page to load jQuery library ( If it is not already loaded),

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
查看更多
登录 后发表回答