Setting text input's value from ViewBag? ASP.NET MVC5

Nick picture Nick · Aug 19, 2014 · Viewed 31.2k times · Source

I am passing a variable ViewBag.crimeRef from my controller and am using it to display a message which works fine:

@if(ViewBag.crimeRef != null)
{
    <div class="alert alert-dismissable alert-danger">
      <button type="button" class="close" data-dismiss="alert">×</button>
      Sorry, there are no matching results for the crime reference <strong>@ViewBag.crimeRef</strong>. Please try searching again.
    </div>    
}

I figured I could use the same methodology to populate the input's value too, however I'm getting a CS1002: ; expected error:

<input type="text" class="form-control" maxlength="11" id="crimeRef" name="crimeRef" placeholder="Crime reference"
        @if(ViewBag.crimeRef != null) { value="@ViewBag.crimeRef" }>

Is there anyway I can populate the input's value using the ViewBag variable?

Many thanks

Answer

Kartikeya Khosla picture Kartikeya Khosla · Aug 19, 2014

Answer 1 :-

<input type="text" class="form-control" maxlength="11" id="crimeRef" 
name="crimeRef" placeholder="Crime reference" 
value="@(ViewBag.crimeRef ?? String.Empty)" >

Answer 2 :-

I m including Nick's answer here because this is the accepted answer, so it will help other stackoverflow users to get answer of their question at one place.

Conditional statements are actually built into Razor as of MVC4 :

Conditional HTML Attributes using Razor MVC3

So simply using this:

<input type="text" class="form-control" maxlength="11" id="crimeRef" name="crimeRef" placeholder="Crime reference"
value="@(ViewBag.crimeRef)">

Will only render the value attribute if ViewBag.crimeRef isn't null - perfect!