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







1 comment:

  1. Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.
    Data Science Training in Indira nagar
    Data Science Training in btm layout
    Data Science Training in Kalyan nagar
    Data Science training in Indira nagar
    Data Science Training in Marathahalli

    ReplyDelete