2012-05-02 16 views
32

Ho la seguente vista ,, che crea 10 ajax.beginform ,, Ma il problema che sto affrontando è che in caso di errore si verifica durante la creazione dell'oggetto quindi il ModelState .AddModelError non verrà mostrato nella vista, anche se ho impostato la @Html.ValidationSummary(true) la vista sembra seguireModelState.AddModelError non viene visualizzato nella mia vista

@model Medical.Models.VisitLabResult 

@for (int item = 0; item < 10; item++) 
{ 
    <tr id = @item> 
    @using (Ajax.BeginForm("CreateAll", "VisitLabResult", new AjaxOptions 
    { 
     HttpMethod = "Post", 
     UpdateTargetId = item.ToString() + "td", 
     InsertionMode = InsertionMode.Replace, 
     LoadingElementId = "progress2", 
     OnSuccess = string.Format(
      "disableform({0})", 
      Json.Encode(item)), 
    })) 
    { 
     @Html.ValidationSummary(true) 

     @Html.AntiForgeryToken() 
     <td> 
      @Html.DropDownList("LabTestID", String.Empty) 
      @Html.ValidationMessageFor(model => model.LabTestID) 
     </td> 
     <td> 
      @Html.EditorFor(model => model.Result) 
      @Html.ValidationMessageFor(model => model.Result) 
     </td> 

     <td> 
      @Html.EditorFor(model => model.DateTaken) 
      @Html.ValidationMessageFor(model => model.DateTaken) 
     </td> 

     <td> 
      @Html.EditorFor(model => model.Comment) 
      @Html.ValidationMessageFor(model => model.Comment) 
     </td> 

     <td> 
      <input type="submit" value="Create" /> 
     </td> 

     <td id = @(item.ToString() + "td")> 
     </td> 
    } 
    </tr> 
    } 
</table> 

E il mio metodo di azione che definisce il ModelState.AddModelError appare come segue: -

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult CreateAll(VisitLabResult vlr, int visitid = 28) 
{ 
    try 
    { 
     if (ModelState.IsValid) 
     { 
      var v = repository.GetVisit(visitid); 
      if (!(v.EligableToStart(User.Identity.Name))){ 
       return View("NotFound"); 
      } 
      vlr.VisitID = visitid; 
      repository.AddVisitLabResult(vlr); 
      repository.Save(); 

      return Content("Addedd Succsfully"); 
     } 
    } 
    catch (DbUpdateException) 
    { 
     JsonRequestBehavior.AllowGet); 
     ModelState.AddModelError(string.Empty, "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests"); 
    } 
} 

Così come posso mostrare ModelState.AddModelError sulla mia vista.

risposta

57


vi invito a cambiare il vostro check try{ } catch(){ }

E prima se esiste una visita per l'id e se così semplicemente restituisce il modello, con l'errore di modello aggiunto

if (visitExists) 
    { 
     ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests"); 
     return View(vlr);  
    } 
    //Other code here 

Cambia la tua AddModelError Per

ModelState.AddModelError("CustomError", "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests"); 

E secondo lei è sufficiente aggiungere un

@Html.ValidationMessage("CustomError") 

Poi quando si torna il tuo modello sarà visualizzato l'errore in cui è stato collocato il @ Html.ValidationMessage ...

+0

Come ti gestire il codice html avvolgendo il messaggio di errore? Si desidera solo che l'HTML (avviso di bootstrap, ad esempio) mostri quando c'è un errore. – Ciwan

8

@Html.ValidationSummary(true) mostra solo il messaggio di errore relativo propertys di modello, se si vuole mostrare anche il messaggio aggiunto, ha aggiunto con

ModelState.AddModelError(
    "CustomError", 
    "The Same test Type might have been already created, go back to the Visit page to see the avilalbe Lab Tests"); 

è necessario impostare @Html.ValidationSummary(false) Se è necessario dis riprodurre il messaggio di convalida vicino ai campi di immissione che è necessario impostare @Html.ValidationSummary(true) e seguire i passaggi suggeriti da Syneryx

5

È possibile utilizzare il dizionario da ViewData in Visualizza per accedere ai dati ModelState.

Ad esempio:

in azione:

ModelState.AddModelError("CustomError", "Error 1"); 
ModelState.AddModelError("CustomError", "Error 2"); 

e per ottenere il messaggio "Errore 1":

ViewData.ModelState["CustomError"].Errors[0].ErrorMessage 
Problemi correlati