JSON / MVC (3P1) HttpPost - not getting it to work

2019-05-24 06:31发布

问题:

In mixing and matching older tutorials with recent posts on MVC 3 Preview 1, I run into the following problem. I am trying to move to JSON-driven edits of my Fighter model (and the underlying db) instead of 'plain old' edits without JSON.

I have an edit view (that uses a Shared EditorTemplate, fighter.ascx) setup for my Fighter class (which exists in an EF 4 model).

On this I have 2 buttons. One 'old' one, which is a submit that calls my editcontroller without JSON, and one is a new one, for which I've written a new HttpPost ActionResult

The old button works: the new button is only half-implemented but already I can see that the ActionResult UpdateJsonTrick is not receiving the data from the view correctly. The returnMessage string reads: "Created fighter '' in the system." Before I can do anything useful in that ActionResult, I've got to know how to pass that data. Where am I going wrong?

So, the edit.aspx is just a simple Html.EditorForModel("Fighter") statement, but here is the Fighter.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Mvc3_EF_BW_Fight.Models.Fighter>" %>
<% using (Html.BeginForm())
   {%>
<%: Html.ValidationSummary(true) %>
<script type="text/javascript" src="../../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../../Scripts/json2.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        $("#JSONTRICK").click(function (event) {

            var fighter = { Id: $('#Id').val(),
                FighterName: $('#FighterName').val(),
                FighterStyleDescription: $('#FighterStyleDescription').val(),
                FighterLongDescription: $('#FighterLongDescription').val()

            };

            $.ajax({
                url: '/Barracks/UpdateJsonTrick',
                type: "POST",
                data: JSON.stringify(fighter),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    // get the result and do some magic with it
                    var message = data.Message;
                    $("#resultMessage").html(message);
                },
                error: function () {
                    $('#message').html('oops Error').fadeIn();
                }
            });

            return false;
        });


    });
</script>
<fieldset>
    <legend>Fighter template</legend>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.Id) %>
    </div>
    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.Id) %>
        <%: Html.ValidationMessageFor(model => model.Id) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.FighterName) %>
    </div>
    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.FighterName) %>
        <%: Html.ValidationMessageFor(model => model.FighterName) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.FighterStyleDescription) %>
    </div>
    <div class="editor-field">
        <%: Html.TextBoxFor(model => model.FighterStyleDescription) %>
        <%: Html.ValidationMessageFor(model => model.FighterStyleDescription) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.FighterLongDescription) %>
    </div>
    <div class="editor-field">
        <%: Html.TextAreaFor(model => model.FighterLongDescription) %>
        <%: Html.ValidationMessageFor(model => model.FighterLongDescription) %>
    </div>
    <p>
        <input type="submit" value="Save" id="save" />
    </p>
    <p>
        <input type="submit" value="JSONTRICK" id="JSONTRICK" />
        <label id="message">
            message</label>
    </p>
    <div>
        <span id="resultMessage"></span>
    </div>
</fieldset>
<% } %>

And here is the (relevant bit from the) controller:

[HttpPost]
public ActionResult Edit(int id, FormCollection collection) //Works
{
   var fighter = _FightDb.Fighters.Single(f => f.Id == id);

    try
    {
        UpdateModel(fighter);
        //var x = ViewData.GetModelStateErrors();
        _FightDb.SaveChanges();

        return RedirectToAction("Index");
    }
    catch
    {
        var viewModel = _FightDb.Fighters.Single(f => f.Id == id);  //fighter;

        return View(viewModel);
    }

}

[HttpPost]
public ActionResult UpdateJsonTrick(Fighter fighter) //doesn't work
{
    var x = ViewData.GetModelStateErrors();
    string returnMessage = string.Format("Created fighter '{0}' in the system.", fighter.FighterName);
    return Json(new PersonViewModel { Message = returnMessage });

}

Thanks for your patience, if you need additional code or information, I can supply.

回答1:

There's a bug in MVC 3 Preview 1 where the JsonValueProviderFactory is not registered by default.

Having something like this in your Global.asax should help:

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())