Загрузите модель в виде формы и отредактируйте ее - PullRequest
0 голосов
/ 22 ноября 2018

У меня проблема с моими 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>
}

Ответы [ 2 ]

0 голосов
/ 22 ноября 2018

Как функция узнает, что такое NameFirst, NameLast и вежливость?Вы никогда не передаете их функции?

Попробуйте удалить

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
            }
        })
     }
 }
0 голосов
/ 22 ноября 2018

Я думаю, что вы должны использовать URL без имени домена

url: "/ Members / GetMember /"

теперь попробуйте

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...