Creando Html Helper usando razor para buscar

I have created a Html helper for searching text given by the user using Razor helper inline. The code i have written is as follows;

<script type="text/javascript">
    $('#companyName').change(function () {
        var searchTerm = $(this).val();
        @Search(searchTerm);
    });
</script>

<p>Search For:</p>
@Html.TextBox("companyName", Model)

@helper Search(string searchTerm)
 {
    if (searchTerm !="" || searchTerm != null)
    {
        @searchTerm;
    }
    else
    {
        @searchTerm.Substring(0, 7)<text>...</text>
    }
    }

Here i want to pass the value of textbox to the searchTerm. How can I do that..?

preguntado el 04 de julio de 12 a las 08:07

html helper works at server-side. JavaScript works at client-side. You cannot call html helper from JavaScript like that, it simply does not exist there -

i think you are looking for a templating solution ... search for jquery templates -

1 Respuestas

Razor helpers execute at the server. In your case you are subscribing to the .change() evento del textbox on the client. So you need to write a client side javascript handler, not a Razor helper:

<script type="text/javascript">
    $('#companyName').change(function () {
        var searchTerm = $(this).val();
        Search(searchTerm);
    });

    function Search(searchTerm) {
        // do the search here
    }
</script>

<p>Search For:</p>
@Html.TextBox("companyName", Model)

Respondido 04 Jul 12, 08:07

Thank you for the suggestion. But I want to create a helper file named search where the argument is the searchTerm, which is passed from the textbox in the view. Can you provide me a better solution for that? - Suraj Shrestha

What are you trying to achieve precisely? You want to invoke a controller action when the user changes something into the textbox? - darin dimitrov

Yes, I want to create something like @Html.Search(argument) so that the argument from view is passed to the controller. - Suraj Shrestha

In this case put your textbox inside a form: @using (Html.BeginForm("SomeAction", "SomeController")) { @Html.TextBox("companyName", Model) }. Now you could subscribe to the .change event of the textbox as you did and submit the containing form: $(this).closest('form').submit();. I don't understand what helper you are trying to write. - darin dimitrov

Thank you for the suggestion... I've used a button to submit and is working and I would like to create helper which will replace @Html.TextboxFor(arguments) with @Html.Search(arguments).. for example @using Html.search(searchTerm) { code to show popup box containg the data related to searchterm} - Suraj Shrestha

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.