Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from view model to javascript function?

For example I have the following model which I am passing a list of to the view:

public class ExampleViewModel
{
    public int id { get; set; }
    public string name { get; set; }

}

In my view I have the following:

@model List<ExampleViewModel>

<table>
    <tr>
        <th>Name</th>
        <th>Action</th>
    </tr>
    @foreach (var x in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(m => x.name)
            </td>
            <td> 
                <input type="button" onclick="edit();" value="Edit">
            </td>
        </tr>
    }
</table>

<script type="text/javascript">
    function edit(x) {
        window.location = "/Home/Edit?id=" + x
    }
</script>

What I am having trouble with is passing x.id to the edit() function. I expected:

<input type="button" onclick="edit(@x.id);" value="Edit">

to work but it did not.

Thanks

like image 646
user1857900 Avatar asked Aug 31 '25 21:08

user1857900


1 Answers

Try this

<input type="button" onclick="edit(@x.id);" value="Edit">
like image 200
Amit Avatar answered Sep 04 '25 05:09

Amit