JAX
JAX

Reputation: 1620

Processing textual inputs in the client side

Using ASP.NET MVC 5 and Razor view engine, is there a way to get the values of input fields before posting the data to the server, processing them and then sending the processed data instead?

For example:

@using (@Html.BeginForm("ViewPage", "Home", FormMethod.Post)) {
     @Html.TextBox("Field1")
     @Html.Hidden("Field2");
     <input type="submit" id="HiddenButton" value="Submit" style="display:none" />
     <input type="button" id="VisibleButton" value="Submit" />    
}

and now :

<script type="text/javascript">
     document.ready(function() {
        $("#VisibleButton").click(function() {
             var Temp = $("#Field1").val()
             @{
                 // C# Area
                 Processing the Temp, by for example calling an extension method and
                 assigning the new value to the Hidden Field
              }
              $("#HiddenButton").trigger("click")
        })
     })
</script>

I'd like to do this , because I wanna encrypt a text before sending it to the server and I've already made my encryption method in C#.

Upvotes: 0

Views: 51

Answers (3)

Andrzej Gis
Andrzej Gis

Reputation: 14306

You can't use C# to perform client-side validation. That's because client-side validation runs on users browser which only understands JavaScript and Html generated earlier by your C# code on the server.

Like Darin said, If you want to perform the validation in C#, you have to do in on server-side. For that you have to perform an ajax call and interpret the result in JavaScript.

One way is to do this the way Darin' shown. The other is to use a MVC built-in mechanism described here.

Upvotes: 0

Amir Popovich
Amir Popovich

Reputation: 29836

You can't really do this..
There is no magic here since JS code runs on the client's end and C# code is located in the server.

You can always use https for an encrypted session.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

This is possible but the processing should happen on the client using javascript:

$("#VisibleButton").click(function() {
    var Temp = $("#Field1").val();

    // process Temp here using javascript
    Temp = 'some new value';

    // set the processed value back to the input field
    $("#Field1").val(Temp);

    $("form").submit();
});

If you want the processing to happen on the server for some reasons, you could send it as an AJAX request to a controller action:

$("#VisibleButton").click(function() {
    var temp = $("#Field1").val();

    $.ajax({
        url: '@Url.Action("SomeAction")',
        data: { value: temp },
        success: function(result) {
            $("#Field1").val(result);
            $("form").submit();
        }
    });
});

And your controller action:

public ActionResult SomeAction(string value)
{
    // do your processing here 
    value = "some new value";

    return Json(value);
}

Upvotes: 1

Related Questions