john smith
john smith

Reputation: 31

display attribute conditionally asp.net mvc with html helper

i want to display attribute with condition for example if the previous label(number) is 1 so the second(price) should be automatically 4

1-4;

2-5;

3-14,

 @Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
    @Html.LabelFor(model => model.number, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.number,listItems, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.number, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.price, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.price, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.price, "", new { @class = "text-danger" })
    </div>
</div>

Upvotes: 1

Views: 92

Answers (1)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

You can use Jquery to handle event dropdown list of number changing.

It look like:

var $number = $("#number"); 
$number.on("change", function(){
         // do something here
});

And then, you assign value for price accordingly.

var number = parseInt($(this).val(), 10);

var priceAccordingTo = 0;
switch(number){
    case 1: priceAccordingTo = 4; break;
    case 2: priceAccordingTo = 5; break;
    case 3: priceAccordingTo = 14; break;
    }
$("#price").val(priceAccordingTo);

Here is the link for demo.

Upvotes: 1

Related Questions