如何将值从Javascript生成的按钮传递给控制器​​?

我的代码生成了一个表格,该表格的每一行末尾都有一个按钮。当用户单击按钮时,如何通过按钮将属性传递u.userEmail给控制器?发送到控制器的值是否为字符串?


我的(无效的)尝试:


    <script>


        $(document.body).append("waiting on async table to load<br>");


        $(document).ready(function () {

            $.getJSON("/Account/LoadClaimsTable", function (crewResponse) {

                //returns a List<UserClaims>

                $(document.body).append("<table>")

                crewResponse.forEach(function (u) {

                    var s = "";

                    s+="<tr><td>" + u.userEmail + "</td>";

                    u.userClaims.forEach(function (k) {

                        console.log("added claim"+k.value);

                        s += ("<td>" + k.type + "</td><td>" + k.value + "</td><td>" +

                            "<input type=\"hidden\" name=\"userEmail\" value=\"`${u.userEmail}`\" />"+

                            "<input type=\"button\" value=\"Create\" onclick=\"location.href='@Url.Action("EditClaims", "Account")'" />

+"</td>");

                    });

                    s += "</tr>";

                    $(document.body).append(s);

                    s = "";

                });

                $(document.body).append("</table>")

            });

        });

    </script>

AccountController.cs包含:


    public ActionResult EditClaims(string userEmail)

    {

        return View("StringView", userEmail);

    }


慕容708150
浏览 202回答 3
3回答

繁花不似锦

您似乎采用的方法是Ajax,响应,渲染模板。话虽如此,您可能需要重新考虑您的方法。步骤1。建立范本<template id="...">&nbsp; &nbsp; &nbsp;<button type="button" value="[action]" onclick="[url]">[text]</button></template>第2步。创建您的请求。axios.get('...').then((response) => {&nbsp; &nbsp; &nbsp;// Retrieve template.&nbsp; &nbsp; &nbsp;// Replace bracket with response object model data.&nbsp; &nbsp; &nbsp;html += template.replace('[action]', response.action);});第三步让JavaScript呈现您的模板。上面的代码可以创建一个清晰简洁的代码库,该代码库在范围更改时更易于维护和扩展,而不是单个请求通过嵌入式标记执行更改。这种方法对我来说效果很好,而且我认为它将使您的疑难解答和定义变得更容易,因为控制器将对象移交给JavaScript,而不是标记/视图数据。这将是对前端的更好的有限控制,并在将来进行明确的修改。

烙印99

有多种方法可以做到这一点。费利佩在上面的答案中提到了一个。这是使用不干扰js的另一种替代方法将电子邮件作为html5数据属性以及另一个我们将用于绑定点击行为的属性添加到按钮。u.userClaims.forEach(function (k) {&nbsp; &nbsp; &nbsp;// Add quotes as needed if you want multiline ( i just removed those)&nbsp; &nbsp; &nbsp;s += "<td>" + k.type + "</td><td>" + k.value + "</td><td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<input type='button'&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;clickablebutton data-email='" + u.email + "' value='Create'/></td>";});现在,在准备好文档的过程中,将click事件处理程序绑定到那些元素(具有我们的custom属性),并读取data属性并构建所需的url。$(document).on("click", "input[clickablebutton]", function (e){&nbsp; &nbsp; var url = '@Url.Action("EditClaims", "Accounts")?useremail=' + $(this).data("email");&nbsp; &nbsp; window.location.href = url;});其他一些建议使用适当的元素。按钮胜于输入(考虑辅助功能)如果用于导航,请使用锚标记而不是按钮。内联JavaScript并不是很好。让浏览器解析您的标记而不会造成任何干扰,然后您可以稍后添加行为脚本(这是uobutrisive js方法的重点)
打开App,查看更多内容
随时随地看视频慕课网APP