Pages

Banner 468 x 60px

 

Tuesday, 4 September 2012

How to get MVC Razor view Controls ID from Java script

In this post I will explain How to get MVC Razor view controller id from JavaScript .In real time some time we need to assign  value to controller or we need to read (get) value from controller.

Example The view have Following Controller
@model MvcApplication1.Models.User
@{
    ViewBag.Title = "create";
}
<h2>
    create</h2>
@using (Html.BeginForm())
{

    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>

          <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>
        <div id="divResult" class="editor-field">
        </div>
        <p>
            <input type="button" id="Create" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Now I will explain how to get controller value from JavaScript with out hard code. Add following script to @Section Scripts
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
        $(function () {
            $('#Create').click(function () {

                var userElement = $('#@(Html.IdFor(m => m.UserName))')
                var result = '';
                result = 'The UserName Text box ID is =<strong>' + '@(Html.IdFor(m => m.UserName))' + '</strong></br>';
                result += 'The UserName Text Value is =<strong>' + userElement.val() + '</strong></br>';
                document.getElementById('divResult').innerHTML = result;
                return false;
            });
        });
    </script>
}



Before Button Click
After Button click

No comments:

Post a Comment