English 中文(简体)
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() { document.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.





相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签