【问题标题】:Load a model in a form view and edit it在表单视图中加载模型并进行编辑
【发布时间】:2019-04-25 01:25:16
【问题描述】:

我的 ajax 请求有问题,我找不到接收控制器模型的方法。 我搜索了互联网,但没有找到可以解决我问题的答案。

我要做的是在我的表单中显示“结果”中包含的数据(姓名、名字和礼貌)。 然后我希望用户修改这些数据并点击“提交”按钮发送我的 POST 请求。

我的方法看起来是正确的(至少是 GET),我很确定我的问题来自我使用 ajax 的方式。

您能告诉我要编辑的代码吗?

提前谢谢你!

控制器

[HttpGet]
public async Task<IActionResult> GetMember(int id)
{


    try
    {
    FileMakerRestClient client = new FileMakerRestClient("https://fms171.hostmy.solutions", "helloJAK", userName, password);
    var toFind = new Models.Members { Zkp_WEB = id };
    var results = await client.FindAsync(toFind);
        Console.WriteLine(results);    
        bool isEmpty = !results.Any();
        if (isEmpty)
        {
            return NotFound();
        }
        Console.WriteLine(results);
        return View(results);
    }
    catch
    {
        return BadRequest();
    }
}


[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GetMember(Models.Members model)
{
    if (ModelState.IsValid)
    {
        FileMakerRestClient client = new FileMakerRestClient("https://fms171.hostmy.solutions", "helloJAK", userName, password);
        var toCreate = new Models.Members { NameFirst = model.NameFirst, NameLast = model.NameLast, Politeness = model.Politeness };
        var results = await client.CreateAsync(toCreate);


        return Ok(results.Response);
    }
    else return BadRequest();
}

查看

@model jak.formulaire.Models.Members


<div id="myForm">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Politeness, "Politeness", htmlAttributes: new { @class = "control-label col-md-4" })
        @Html.EditorFor(model => model.Politeness, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter politeness", @id = "Politeness" } })
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    @Html.ValidationMessageFor(model => model.Politeness, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Zkp_WEB, "Id", htmlAttributes: new { @class = "control-label col-md-4" })
        @Html.EditorFor(model => model.Zkp_WEB, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter id", @id = "idMember" } })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.NameFirst, "First name", htmlAttributes: new { @class = "control-label col-md-4" })
        @Html.EditorFor(model => model.NameFirst, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter first name", @id = "NameFirst" } })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.NameLast, "Last name", htmlAttributes: new { @class = "control-label col-md-4" })
        @Html.EditorFor(model => model.NameLast, new { htmlAttributes = new { @class = "form-control", @placeholder = "Enter last name", @id = "NameLast" } })
    </div>

    <br /><br />
    <button type="submit" class="btn btn-primary" id="btnEdit">Submit</button>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
@section Scripts{


    <script type="text/javascript">

        $(document).ready(function () {
            GetMember();
            Edit();

        }); 

        function GetMember() {

            //$('#btnEdit').click(function () {
            //    var idMember = $('#idMember').val();

                $.ajax({
                    type: "GET",
                    url: "https://localhost:44338/Members/GetMember/" + 2,
                    dataType: "json"


                });
            //});
        }

        function Edit() {

            $('#btnEdit').on('click', function () {
                var idMember = $('#idMember').val();

                myFormdata = {
                    Politeness: Politeness,
                    NameFirst: NameFirst,
                    NameLast: NameLast
                };

                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "https://localhost:44338/Members/GetMember/",
                    data: JSON.stringify(myFormdata),
                    dataType: "json" ,
                    success: function (data) {
                        if (data === "success") {
                            alert("User successfully modified");
                        }
                    },
                    error: function (error) {
                        alert('error');
                    }
                });
            });
        }

    </script>
}

【问题讨论】:

    标签: c# jquery asp.net-mvc asp.net-ajax


    【解决方案1】:

    我认为你应该使用不带域名的 url

    网址:“/Members/GetMember/”

    现在试试

    【讨论】:

    • 同样的结果,实际上 ajax 找到了好的路线,但我的问题是当 ajax 必须处理我的方法的返回时。
    • 所以你控制台你的返回对象它返回了什么
    • 我的返回值是一个 IEnumarable,其中包含好成员的姓氏、名字、礼貌。
    • 我认为您在初始化 formdata 对象时确实缺少 'var'
    • 并在控制器上提交 [ValidateAntiForgeryToken]
    【解决方案2】:

    函数如何知道 NameFirst、NameLast 和 Politeness 是什么?你从来没有将它们传递给函数?

    尝试删除

    contentType
    

    dataType
    

    来自这个 ajax 调用。

                    $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "https://localhost:44338/Members/GetMember/",
                    data: JSON.stringify(myFormdata),
                    dataType: "json" ,
                    success: function (data) {
                        if (data === "success") {
                            alert("User successfully modified");
                        }
                    },
                    error: function (error) {
                        alert('error');
                    }
                });
    

    将模型传递给控制器​​似乎对我来说很好。

    执行此操作的更好方法是执行以下操作:

    1) 将表单包装在 Html.BeginForm 中

    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "//form ID" }))
    {
         //You form HTML code
    }
    

    2) 有这样的功能:

    $(function () {
        $("//form ID").submit(function (event){
            event.preventDefault();
    
            //Your code to call the controller
            //Just serialize the form like this
            var formData = $("//form ID").serialize();
    
            $.ajax({
                url:'@Url.Action("Method", "Controller")',
                type:'POST',
                data: formData,
                success:function(result){
                    //Whatever
                }
            })
         }
     }
    

    【讨论】:

    • 我也在我的控制器中收到了模型,但是 NameFirst、nameLast 和 Politeness 为空:(
    • @Korpin 看看我的答案的编辑。而不是序列化 myFormdata,只需序列化表单。此外,javascript 将如何知道 NameFirst、NameLast 和 Politeness 是什么。您永远不会将它们传递给函数。
    • 完美,现在很好用! POST 解决了!对于不向我的表单发送信息的 Get 方法有什么猜测吗?
    猜你喜欢
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多