开发者

Json results prompting "Save As" dialog in browser instead of being processed. ASP.NET MVC

I know this has been an issue for others, but I've yet to find anything that fixes my problem.

I have a partial view that is displayed in a lightbox (colorbox). It is a simple form. I want the form to submit and return a little bit of data. The data will be used in calling subsequent functions, and I want the main DIV just to be updated with a "success" message. Here is the full code of the partial view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Solution2.Models.Category>" %>

<script type="text/javascript">
    $('propcatform').submit(function(e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url:  $(this).attr("action"),
            data: $(this).serialize(),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function(data) { document.getElementById('main1').innerHTML = "Success"; },
            failure: function() { do开发者_StackOverflow中文版cument.getElementById('main1').innerHTML = "Failure"; }
        })
    });
    </script>

    <% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "propcatform", name = "propcatform" }))
       {%>
        <div id="main1">
        <fieldset>
            <legend>Fields</legend>
            <p>
                <label for="CatTitle">Category Title:</label>
                <%= Html.TextBox("CatTitle") %>
                <%= Html.ValidationMessage("CatTitle", "*") %>
            </p>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
        </div>

    <% } %>

Here is my controller code. The code works, in that it successfully adds the form data to the table/database. What exactly should my "return" line look like?

[AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Create(Category propcat)
        {

            Category resultcat = new Category();
            _db.Categories.InsertOnSubmit(propcat);
            _db.SubmitChanges();
            resultcat = propcat;
            return Json(new { CatID = resultcat.CatID, CatTitle = resultcat.CatTitle, message = "Category successfully created!" });
        }

Currently I'm not actually using any of the result data in my partial view code (even though I reference it in my "success" parameter). I'm just trying to get it to work (and not prompt me to save the results).

Thanks.


Typically you're not going to return Json to the user's browser directly through a normal form submittal. It's a great way to pass information that you plan to digest internally (as you describe) but doing what you show above will spit back Json data to the user which just looks like.... Javscript -- it's not valid HTML and depending on how the browser is configured, it may pop-up a "Save As" dialogue.

In your example, you could try to have the default action be to return the Create view and have a check like this:

if (Request.IsAjaxRequest())
{
  return Json(.......);
}
else
{
  return View(....);
}

...and change your function return type to ActionResult.

This will ensure that the initial load of the page displays the actual View. Ajax calls to the same page (from buttons on the page) will return just the Json data that you're interested in.

UPDATE:

If the action should display the same page except for the updated Json content, I'd recommend not using a Submit button. Just use a normal input button and bind the click action to your jQuery.ajax call. The data will be received from the Create/POST action and will populate per the success: clause in the Ajax call.


I've had the same issue and this worked for me:

return new JsonResult
{
  ContentType = "text/html",
  Data = new { foo = 1, bar = "Something" }
};

Explicitly create a new JsonResult object, set the ContentType and return that, instead of using the Json method.


Use Firefox + Firebug.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜