Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can JQuery use a model?

@using(Html.BeginForm())
   {
        <fieldset>
    <p>
    <label for="Title">Referans Adı</label>
    <p>
    @Html.TextBoxFor(Model=> Model.Name)
    </p>

How can the model's data be used in javascript like used in the html form?

Can javascript use the model data like used in html from?(like Model.Name)

like image 317
Sesen Avatar asked May 26 '11 14:05

Sesen


2 Answers

Yes. Razor can parse the following just fine:

<script type="text/javascript">    
    $(document).ready(function() {
      alert("@Model.Name");
    }    
</script>
like image 116
Brandon Avatar answered Oct 03 '22 18:10

Brandon


If you want to keep the javascript in a separate .js file instead of in your view, you can use a hidden field to store the value.

<input type="hidden" id="name-hidden" value="@Model.Name" />

You can then access it in javascript by using the id. For instance, in jQuery:

$(document).ready({
    var $nameHidden = $('#name-hidden');
    alert('Old Name: ' + $nameHidden.val());

    $nameHidden.val('Some New Name');
    alert('New Name: ' + $nameHidden.val());
});
like image 41
AaronShockley Avatar answered Oct 03 '22 18:10

AaronShockley