SPN
SPN

Reputation: 13

How to get select option value inside razor in mvc

I have a <select> tag in my view. For example:

<html><head></head>
<body>
 <div>
 <select>
  <option value="">Select</option>
  <option value="alert1">Alert1</option>
  <option value="alert2">alert2</option>
 </select> 
 </div>
 <div id="preview">
  `enter razor code here`@ {            
    here i have to write condition based on
    the <select option> tag value,
    need to display respective viewbag.
  }
 </div>
</body></html>

From my controller I am passing a viewbag, e.g.:

 viewbag.alert1="some html template1".
 viewbag.alert2="some html template2".

My requirement is:

On selecting <option>, say if I select 'Alert1', then in the <div id="preview"> I need to display the viewbag.alert1 content. If the user selects 'Alert2' then in the <div id="preview"> I need to display viewbag.alert2 value.

I know, I can use @Html.Raw(ViewBag.alert1) and @Html.Raw(ViewBag.alert2) to get the data but it should be displayed based on the value of <select option> tag. Inside razor tag, I need to get the value of the <select> tag

Upvotes: 0

Views: 1523

Answers (1)

InfinityGoesAround
InfinityGoesAround

Reputation: 1021

Something like this:

@if (ViewBag.alert1 != null || ViewBag.alert2 != null)
{
    @if(ViewBag.alert1.Selected == true)
    { 
      ViewBag.alert.value;
    }
    @if(ViewBag.alert2.Selected == true)
    { 
      ViewBag.alert2.value;
    }
}

Upvotes: 1

Related Questions