call razor function from javascript

2019-07-11 02:48发布

问题:

I'm creating a website with razor with a database but I have a problem changing database elements from within the webpage.

All elements are shown in a table with an update button. If the button is clicked, it sends it's ID to a JavaScript function. In that function an array is created with all the necessary properties. Then I want to pass that array to my razor function, but when calling the function in JavaScript, I get an error (The name 'kamer' does not exist in the current context). Anyone knows a solution?

thanks!

my razor function:

@functions{
public String saveRoom(string[] room){
    var db = Database.Open("Studentenkamers"); 

    var sql = "UPDATE Studentkamer SET oppervlakte='" + room[1] + "', locatie='" + room[2] + "', type='" + room[3] + "', vrij='" + room[4] + "' WHERE id='" + room[0] + "'";
    db.Query(sql);     
    return "ok";

}

}

the html and javascript code:

@foreach(var row in db.Query(getKamers))
     {            
        <tr id="@row.id">
            <td class="td-id">@row.id</td>
            <td class="td-opp"><input type="text" value="@row.oppervlakte" name="oppervlakte" id="td-opp" /></td>
            <td class="td-loc">@row.locatie</td>
            <td class="td-type"><input type="text" value="@row.type" name="type" id="td-type" /></td>
            <td class="td-kamernr">@row.kamernr</td>
            <td class="td-vrij"><input type="text" value="@row.vrij" name="vrij" id="td-vrij" /></td>
            <td class="td-update"><input type="button" value="opslaan" onclick="updateRoom(this.id)" name="opslaan" id="@row.id" /></td>
       </tr>               
     }
    </table>
    <script type="text/javascript">

        function updateRoom(id) {               
            var opp = $("#" + id + " .td-opp input").attr("value");
            var locatie = $("#" + id + " .td-loc").html();
            var type = $("#" + id + " .td-type input").attr("value");
            var kamernr = $("#" + id + " .td-kamernr").html();
            var vrij = $("#" + id + " .td-vrij input").attr("value");

            var kamer = [id, opp, locatie, type, kamernr, vrij];
            alert(kamer);
            @saveRoom(kamer);
        }
    </script>