ASP.NET MVC Core仅通过Ajax Post向控制器发布字符串 [英] ASP.NET MVC Core posting just a string to controller via Ajax Post

查看:77
本文介绍了ASP.NET MVC Core仅通过Ajax Post向控制器发布字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用Ajax将字符串值发送到Home控制器.以下Ajax调用给出了错误(在Google Chrome开发者工具中):Failed to load resource: the server responded with a status of 404 (Not Found):

Trying to send a string value to Home controller using Ajax. Following Ajax call gives the error (in Google Chrome developer tool): Failed to load resource: the server responded with a status of 404 (Not Found):

$.ajax({
    url: 'Home/TestAction',
    data: "Test data",
    type: 'POST',
    success: function (obj) {
        alert('Suceeded');
    }
});

更新:

之后,我尝试了所有针对该帖子的回复(截至目前)中的url部分,该url正确无误,但我仍然得到一个warning和一个error,如下图所示. 注意:图像中的控制器名称和操作名称不同,但它们位于VS2015中称为Controllers的同一默认文件夹中.我尚未创建任何子文件夹等.此外,这在开发计算机Win10 with VS2015 ASP.NET Core 1.1, IIS EXPRESS上.请单击图像以清楚地看到消息.

After I've tried the url part from all the responses (as of now) to this post, the url turns out to be correct but I'm still getting a warning and an error as shown in the image below. NOTE: The names of the controller and action in the image are different but they are in the same default folder called Controllers in VS2015. I've not created any subfolder etc. Also, this is on development machine Win10 with VS2015 ASP.NET Core 1.1, IIS EXPRESS. Please click on the image to be able to see the message in clear.

更新2 :

为了使我的问题更易于理解,我在

To make my question simpler to understand, I've created a test ASP.NET Core app following this official ASP.NET MVC Core tutorial. Please see the error image below.

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Genre,Price,ReleaseDate,Title")] Movie movie)
{
    if (id != movie.ID)
    {
        return NotFound();
    }

    if (ModelState.IsValid)
    {
        try
        {
            _context.Update(movie);
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!MovieExists(movie.ID))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }
        return RedirectToAction("Index");
    }
    return View(movie);
}

查看 [.. \ views \ movies \ Index.cshtml].注意:我只在最后添加了一个额外的按钮<button type="button" id="testid" class="Savebtn">Test</button> Ajax呼叫.

View [..\views\movies\Index.cshtml]. NOTE: I've only added an extra button <button type="button" id="testid" class="Savebtn">Test</button> and the Ajax call at the end.

@model MovieGenreViewModel

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<form asp-controller="Movies" asp-action="Index" method="get">
    <p>
        <select asp-for="movieGenre" asp-items="Model.genres">
            <option value="">All</option>
        </select>

        Title: <input type="text" name="SearchString">
        <input type="submit" value="Filter" />
    </p>
</form>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.movies[0].Genre)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.movies[0].Price)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.movies[0].Title)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model.movies) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Genre)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ReleaseDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                <button type="button" id="testid" class="Savebtn">Test</button>
                <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>
@section scripts
{
    <script>
        $(document).ready(function () {

            $('.Savebtn').click(function () {

                    $.ajax({
                        url: '@Url.Action("Edit", "Movies")',
                        data: "Test data",
                        type: 'POST', //POST if you want to save, GET if you want to fetch data from server
                        success: function (obj) {
                            // here comes your response after calling the server
                            alert('Suceeded');
                        },
                        error: function (obj) {
                            alert('Something happened');
                        }
                    });
            });
        });
    </script>
}

[在Google Chrome开发者工具中]错误:

推荐答案

在剃刀模板引擎中未定义JavaScript代码时,以前发布的所有答案似乎都不太灵活且无法正常工作,这在以下情况下适得其反您可以打包/缩小CS/JS文件.

All of the answers posted before seem to be very unflexible and not working, when the JavaScript code is not defined within the razor template engine, which is counter productive when you bundle/minify your cs/js files.

尝试将其添加到标题部分的_Layout.cshtml文件中

Try adding this to your _Layout.cshtml file inside the header section

<head>
    ...
    <base href="~/"/>
</head>

这会将基本URL设置到您的应用程序主目录.所有相对网址都将附加到该基本网址.这也应该与jQuery请求一起使用,因为较新的版本确实遵守了基本标签,因此当您的JavaScript代码未在剃刀(* .cshtml)模板中呈现时,它应该可以很好地工作.

This sets the base url to your application home. All relative urls will be appended to this base url. This should also work with jQuery requests as the newer versions do respect the base-Tag and hence should work well when your JavaScript code is not rendered within the razor (*.cshtml) templates.

好吧...

  1. 问题是您的控制器动作需要电影模型.您无法发送简单的字符串.
  2. 您发布的是MVC操作,它返回一个视图,没有数据.您不能将其用于ajax,因为它将返回HTML代码.对于Ajax,您需要Json对象.

您的操作应类似于

[Route("api/[controller")]
public class MovieController {
    [HttpPost("{id}")]
    public async Task<IActionResult> Edit(int id, [FromBody] Movie movie)
    {
    
    }
}

注意:通常,对于RESTful服务,您可以使用PUT更新/替换资源,然后使用POST创建资源.请参见 URL与HTTP方法之间的关系.

Note: Usually for RESTful services you use PUT to update/replace a resource and POST to create it. See Relationships between URL and HTTP Methods.

和您的jQuery/Ajax请求一样

and your jQuery/Ajax request like

// example movie object, this depends on the definition of your model class on the server
var movie = {
    id: 1,
    name: "Back to the Future", 
    genre: "Sci-Fi"
};
$.ajax({
    url: 'api/movies/'+movie.id,
    data: movie,
    type: 'POST',
    success: function (obj) {
        alert('Suceeded');
    }
});

这篇关于ASP.NET MVC Core仅通过Ajax Post向控制器发布字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆