'How can I show the price according to the selected option without refreshing the page with c#

I have not worked with Ajax so far and I want to show the price after selecting the desired option without refreshing the page.

<div class="form-group">
<label class="control-label">choice your Option</label>
 <select>
       @foreach (var item in Materials)
        {
            <option value="@item.Id">
                @item.MaterialName @item.Panel
             </option>
        }
  </select>
   <span class="main-price ">@item.Price</span>
</div>


Solution 1:[1]

Lets see what we can do here for your case:

Assign an id to your select to hold the value that you will send your server and span to display the output from the server:

<div class="form-group">
    <label class="control-label">choice your Option</label>
     <select id="ddlMaterial">
           @foreach (var item in Materials)
            {
                <option value="@item.Id">
                    @item.MaterialName @item.Panel
                 </option>
            }
      </select>
   <span class="main-price" id="priceDisplay">@item.Price</span>
</div>

Now we define the AJAX call that will send the request to the server. This request will get the current id of the selected option and then covert it to a JSON string which is sent to the server for processing. The url is the action method which will be invoked on this call:

$(document).ready(function () {
    $("#ddlMaterial").change( function (event) {
        var id = $(this).val();
        var json = {id : id}; 
        
        $.ajax({
            type: 'POST',
            url: "@Url.Action("GetPrice", "Home")",
            dataType : "json",
            data: {"json": JSON.stringify(json)},
            success: function(data) {
              if(data.status=="true")
              {
                $("#priceDisplay").text(data.price);
              }
              else
              {
                alert('Some error');
              }
            },
            error: function(data) {
                alert('Some error');
                window.location.reload();
            }
        });
    });
});

And finally your Controller action method will be:

using System.Web.Script.Serialization;

[HttpPost]
public JsonResult GetPrice(string json)
{
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    //Get your variables here from AJAX call
    var id = Convert.ToInt32(jsondata["id"]);
    //Get the price based on your id from DB or API call
    var getMyPrice=GetPrice(id);
    return Json(new {status="true", price= getMyPrice});
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rahul Sharma