$ .AJAX .post()不工作 - 服务器响应状态为404(未找到)?

时间:2015-02-12 20:35:24

标签: jquery ajax asp.net-mvc

我正在开发一个MVC5应用程序的视图。这是一个具有多个属性的Edit视图,其中一些属性与其他模型相关。我有我的主INV_Assets模型,然后是Location, Manufacturer, Model, Status, Type, Vendor等其他几个表格。在这个Edit视图中,我将这些特定属性显示为包含当前所有值的下拉列表这些表格,以及每个列表的[创建新]按钮。

当用户选择[CREATE NEW]按钮时,我会出现一个隐藏的表单,允许用户输入特定Table / DropDown的新值。除了POST之外我一切正常,我将值添加到表中并刷新DropDown列表。

以下是我为第一个下拉列表(Model选择)放在一起的内容 - 一切正常运行到POST:

INV_Assets.Edit查看

<div class="form-group">
        <span class="control-label col-md-2">Manufacturer:</span>
        <div class="col-md-4">
            @Html.DropDownListFor(model => model.Manufacturer_Id, (SelectList)ViewBag.Model_List, htmlAttributes: new { @class = "form-control dropdown" })
            @Html.ValidationMessageFor(model => model.Manufacturer_Id, "", new { @class = "text-danger" })
        </div>
        <div class="col-md-1">
            <div class="btn-group">
                <button type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
            </div>
        </div>
    </div>

INV_Assets.Edit脚本

<script type="text/javascript">

        $(document).ready(function () {
            // Show() form to enter new Model.
            $('#createNewModel').click(function () {
                $('#createModelFormContainer').show();
            })

            // Submit new Model value and refresh dropdown
            $('#submitNewModel').click(function () {
                alert("New Function!"); // WORKING

                var form = $(this).closest('form');
                var url = form.attr('action');
                var data = { Text: form.find('input').first().val() };

                alert("Prior to Post"); // WORKING

                $.post(url, form.serialize(), function (data) {

                    alert("Begin POST!"); // NOT BEING REACHED!

                    $('#selectModel').append($('<option></option>').val(data.ID).text(data.Text));
                    form[0].reset();
                    $('#createModelFormContainer').hide();
                })
            });
        });
</script>

当我的代码遇到$.post时出错了。它之前得到了:

Script1

由于post()似乎是匿名函数,我假设我没有安装ajax。然后我安装了Microsoft.jQuery.Unobtrusive.Ajax,现在将我的错误呈现为:Failed to load resource: the server responded with a status of 404 (Not Found) - http://localhost:4545/INV_Assets

对此有何想法?

据我了解,我的提交应该发布到createNewModel()内的INV_AssetsController方法下面:

    [HttpPost]
    public JsonResult createNewModel(INV_Models model)
    {
        model.created_date = DateTime.Now;
        model.created_by = System.Environment.UserName;
        model.modified_date = DateTime.Now;
        model.modified_by = System.Environment.UserName;

        if (ModelState.IsValid == false && model.Id == 0)
        {
            ModelState.Clear();
        }

        if (ModelState.IsValid)
        {
            db.INV_Models.Add(model);
            db.SaveChangesAsync();
        }

        return Json(new { ID = model.Id, Text = model.model_description });
    }

假设它与我的路由有关,这是我当前的RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

任何拥有更多专业知识的人都能看到我做错了什么?


修改

使用 wahwahwah 的建议,我对我的脚本进行了以下修改:

        $('#createNewModel').click(function () {
            $('#createModelFormContainer').show();
        })

        $('#submitNewModel').click(function () {
            var form = $(this).closest('form');
            var data = { Text: form.find('input').first().val() };
            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: '@Url.Action("createNewModel", "INV_Assets")',
                data: data,
                success: function (resp) {
                    alert("SUCCESS!");
                },
                error: function () {
                    alert("ERROR!");
                }
            });

走这条路线,我的createNewModel()操作在控制器中被正确调用,但在db.SaveChangesAsync()失败:

    [HttpPost]
    public JsonResult createNewModel(INV_Models model)
    {
        model.created_date = DateTime.Now;
        model.created_by = System.Environment.UserName;
        model.modified_date = DateTime.Now;
        model.modified_by = System.Environment.UserName;

        if (ModelState.IsValid == false && model.Id == 0)
        {
            ModelState.Clear();
        }

        if (ModelState.IsValid)
        {
            db.INV_Models.Add(model);
            db.SaveChangesAsync();
        }

        return Json(new { ID = model.Id, Text = model.model_description });
    }

错误如下:

An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

EDIT2

将我麻烦的代码修改为try / catch,然后在ex:

上设置Watch
    [HttpPost]
    public JsonResult createNewModel(INV_Models model)
    {

            model.created_date = DateTime.Now;
            model.created_by = System.Environment.UserName;
            model.modified_date = DateTime.Now;
            model.modified_by = System.Environment.UserName;

            // Set ID
            int lastModelId = db.INV_Models.Max(mdl => mdl.Id);
            model.Id = lastModelId+1;

            if (ModelState.IsValid == false && model.Id > 0)
            {
                ModelState.Clear();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    db.INV_Models.Add(model);
                    db.SaveChangesAsync();}
                catch (Exception ex)
                {
                    Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                }
            }

            return Json(new { ID = model.Id, Text = model.model_description });  
    }

ex详细信息:

DbEntityValidationErrorDetails

显然,为新模型输入的description我没有被包含在正在保存的新Model中?


EDIT3

以下是我当前的脚本/控制器操作代码。当我在控制器内部进入并在?model.model_description中输入Immediate Window时,它会返回null

关于我的以下警报,我的<input type="text" name="model_description" />中的值似乎没有正确存储在变量中以供JSON使用,因此不会传递给控制器​​?

  • alert(test)S2EFXrd3nXdWOIES5eBi4e_Fz3wrqCwP44hhQ7kj_foL3qkNv26OBgQoqHC-8BV8HKC6xdDEa7uCBnhOFPKL3AwIko99p-j_887qQgOXRPg1
  • alert(data.model_description)S2EFXrd3nXdWOIES5eBi4e_Fz3wrqCwP44hhQ7kj_foL3qkNv26OBgQoqHC-8BV8HKC6xdDEa7uCBnhOFPKL3AwIko99p-j_887qQgOXRPg1
  • alert(jasonData.valueOf()){"model_description":"S2EFXrd3nXdWOIES5eBi4e_Fz3wrqCwP44hhQ7kj_foL3qkNv26OBgQoqHC-8BV8HKC6xdDEa7uCBnhOFPKL3AwIko99p-j_887qQgOXRPg1"}

输入表格

            <div id="createModelFormContainer" style="display:none">
                <form action="/createNewModel">
                    <input type="text" name="model_description" />
                    <input type="button" id="submitNewModel" value="Submit" />
                </form>
            </div>

脚本

        $('#submitNewModel').click(function () {

            var form = $(this).closest('form');

            var test = form.find('input').first().val();
            alert(test);

            var data = { model_description: form.find('input').first().val() };
            alert(data.model_description);

            //var data = { model_description: $("input[name = 'model_description']").text.toString() };

            var jsonData = JSON.stringify(data);
            alert(jsonData.valueOf());

            $.ajax({
                type: "POST",
                dataType: "JSON",
                url: '@Url.Action("createNewModel", "INV_Assets")',
                data: jsonData,
                success: function (resp) {
                    alert("SUCCESS!");
                },
                error: function () {
                    alert("ERROR!");
                }
            });

1 个答案:

答案 0 :(得分:2)

以下是一些可能有助于您解决 View / jQuery:

的问题
  1. 确保您实际上发布了JSON
  2. 您在调用`form.find(&#39;输入&#39;)时检索值.first()。val()&#39;
  3. 您要发布到准确的网址
  4. 您发布的JSON对象与控制器中的模型具有相同的属性命名约定
  5. 这是一个例子(不按顺序):

    //... earlier code omitted for brevity
    
    var test = form.find('input').first().val();
    alert(test); // <--- should return the value you want to post (2)
    
    // ... (4) need to change 'Text' to 'model_description' to reflect your model
    // properties (otherwise, how can your controller bind your model to the json object your submitting to it?)
    
    var data = { model: [{ model_description: form.find('input').first().val(); }]};
    
    // need to make data a JSON object (1a)
    
    var jsonData = JSON.stringify(data);
    
    $.ajax({
        type: "POST", //<-- specify POST (1b)
        dataType: "JSON", // <-- specify JSON (1c)
        url: '@Url.Action("createNewModel", "INV_Assets")', // <-- Easier way to do URL (3)
        data: jsonData, // JSON
        success: function(resp){ 
            //callback 
        },
        error: function() {
           //callback
       }
    });
    

    现在,使用控制器...

    切换断点并确保JSON对象绑定到模型对象:

    public JsonResult createNewModel(INV_Models model)
    {
        // jsonData.model_description should have automatically bound to 
        // model.model_description because the property names are the same
    }
    

    关于您的SaveChanges()问题,当出现类型不匹配时,通常会抛出此错误 - 或者需要null数据 - 您可能希望将数据包调用{{{1}然后读取/处理错误:

    try-catch