NealR
NealR

Reputation: 10669

How to determine value of text box in ASP MVC view

Is it possible to access the value of a text box within the same View? For example, in my view I have the following text box

@Html.TextBox("searchValue", ViewBag.CurrentFilter as string, new { placeholder = "Search" })

If a user enters a value, then hits submit, the page will send that search criteria to the controller, query the database based on the criteria, and then display the results back in the view. When the view is rendered again, the text stays in the search box and the tag is rendered

<input id="searchValue" name="searchValue" placeholder="Search" type="text" value="what i just typed in here" />

is there a way for an ASP MVC 3 view to access the value of that text box? I want to create a condition similar to

    @if (searchValue.hasValue())
    {
        do something in here
    }

Upvotes: 1

Views: 1981

Answers (2)

Joel
Joel

Reputation: 647

Maybe I misunderstood, but it looks like you are populating the searchbox with ViewBag.CurrentFilter and then "When the view is rendered again, the text stays in the search box" as "value="what i just typed in here"

Which sounds to me like you already know what the search text is, so why do you need to read the value of the textbox? Why wouldn't the logic be

@if (`ViewBag.CurrentFilter` hasSomeValue)
{
    do something in here
}

Sorry in advance if I missed the point.

Upvotes: 1

Ant P
Ant P

Reputation: 25221

The view is rendered synchronously, when the page first loads. All Razor expressions are evaluated when the page renders, so what you get back is static HTML. You can't use that to track subsequent changes to form values - only to carry out logic based on their initial values for the current response.

You need to use Javascript. Supposing you have a link with an id of myLink. Style it to display:none; by default. Then, with jQuery, you can do the following:

<input id="searchValue" name="searchValue" ... />

<script type="text/javascript">
    $('#searchValue').change(function (){
         if($('#searchValue').val().length > 0) {
             $('#myLink').show();
         } else {
             $('#myLink').hide();
         }
    });
</script>

If you need more complex logic, you could switch out the link with a partial view and update it with AJAX calls.

Upvotes: 2

Related Questions