Frage

Ich habe eine Situation, wo ich Daten an einen Controller über jQuery $ .ajax schicke, sind die Daten eine serialisierte JSON-String. (MVC 3.0)

Es bindet es in Ordnung - mein Controller erhält die Ergebnisse, und sie sind richtig. Nun, ich habe ein Problem damit Validierung Entsendung zurück. Ich vermute, es liegt daran, dass nicht alle meine Objekte nativ Formular-Steuerelemente gebunden sind.

Das Problem ist, dass ich auf ‚Hinzufügen‘ Daten zu meinem Modell mit Hilfe von Javascript, da das Modell ein Element aus einer Sammlung erfordert. Mit Hilfe von JavaScript, jQuery und Templating, ich habe dieses Element ausgewählt, und ich es zum Modell hinzufügen, bevor er sich an den Controller sendet ab. Doch auf dem Postbacks ist diese Daten nicht vorhanden ist (was zu erwarten ist, da es in den JavaScript-Array deserialisieren würde - das ist nicht mein Problem).

Mein Problem ist, dass es eine Doppelpostback für die Validierung durchführt, oder gar keine. Wenn ich e.preventDefault(); verwenden, um die normale Form Entsendung zu stoppen, habe ich nie Validierung erhalten. Aber wenn ich das nicht tun, dann ich immer ein Doppel-Post bekommen, was meiner Ansicht endet nie umgeleitet wird.

Meine jQuery-Code ist wie folgt ..

   $('form').submit(function(e){

    var data = $('form').serializeObject();
    data.Quality = // this line adds some data from a JSON object.

    var json = JSON.stringify(data);

    $.ajax({
      url: location.href,
      type: 'POST',
      dataType: 'json',
      data: json,
      contentType: 'application/json',
      success: function (data) {
       $("#jsonOutput").html(json);
      }
    });

    e.preventDefault();
   });

Hier ist die serializeObject Funktion.

$.fn.serializeObject = function () {
 var o = {};
 var a = this.serializeArray();
 $.each(a, function () {
  if (o[this.name]) {
   if (!o[this.name].push) {
    o[this.name] = [o[this.name]];
   }
   o[this.name].push(this.value || '');
  } else {
   o[this.name] = this.value || '';
  }
 });
 return o;
};

Hier ist meine Controller Aktion.

  [HttpPost]
  public ActionResult Blueprint(Blueprint blueprint)
  {
   if (ModelState.IsValid)
   {
    using (var context = new Mapping.DataContext())
    {
     context.Blueprints.Add(blueprint);
     context.SaveChanges();

     return Json(Redirect("/List/Blueprints")); 
    }
   }

   return View(blueprint);
  }

werde ich mehr Code schreiben, wenn gewünscht, aber ich denke, das ist alles, was relevant ist. Ich bin mit der Bibliothek knockoutjs für das Templat, wenn das überhaupt relevant ist. Bitte sagen Sie mir, was Sie sonst ggf. sehen müssen.

War es hilfreich?

Lösung

 $("#jsonOutput").html(json);

As far as the double post goes, this is happening because the request is being submitted by your event handler and the actual form submit. To get rid of this issue, you want something like this:

$('form').submit(function(e){

    var data = $('form').serializeObject();
    data.Quality = // this line adds some data from a JSON object.

    var json = JSON.stringify(data);

    $.ajax({
      url: location.href,
      type: 'POST',
      dataType: 'json',
      data: json,
      contentType: 'application/json',
      success: function (data) {
       $("#jsonOutput").html(json);
      }
    });

    return false;
   });

return false, will tell the prevent the event from being processed by the form as you are telling the system that you handled it already.

The other issue I see with what you are doing, you are requesting json by setting dataType:'json' This means that your request is expecting a json object, and in the case of failed validation, you are returning a full view. This is probably not what you want to be doing.

Also Note:

$("#jsonOutput").html(json);

Which is being called on successful response is loading the value of the json you are sending with your request and not the data from the response.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top