2012-05-02 7 views
32

Tengo la siguiente vista ,, que crea 10 ajax.beginform ,, pero el problema que estoy enfrentando es que en caso de que ocurra un error durante la creación del objeto, entonces el ModelState .AddModelError no se mostrará en la vista aunque yo he dado la @Html.ValidationSummary(true) la vista se ve como sigueModelState.AddModelError no se muestra dentro de mi 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> 

Y mi método de acción que define el ModelState.AddModelError se ve de la siguiente manera: -

[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"); 
    } 
} 

Entonces, ¿cómo puedo mostrar el ModelState.AddModelError en mi vista.

Respuesta

57


yo le pido a cambiar su cheque try{ } catch(){ }

Y en primer lugar si existe una visita para el ID especificado y si es así, simplemente devuelve el modelo con el error del modelo agregado

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 

Cambiar la AddModelError Para

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

Y en su opinión, sólo tiene que añadir un

@Html.ValidationMessage("CustomError") 

Entonces cuando regrese a su modelo se mostrará el error donde se ha colocado el @ Html.ValidationMessage ...

+0

¿Cómo manejaría el html envolver el mensaje de error? Solo desea que el HTML (alerta de arranque, por ejemplo) se muestre cuando hay un error. – Ciwan

8

@Html.ValidationSummary(true) muestra sólo el mensaje de error acerca propertys del modelo, si desea mostrar también el mensaje añadido, añadido 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"); 

es necesario establecer @Html.ValidationSummary(false) Si necesita dis reproducir el mensaje de validación cerca de los campos de entrada que necesita para establecer @Html.ValidationSummary(true) y seguir los pasos sugeridos por Syneryx

5

Puede usar el diccionario ViewData en Ver para acceder a los datos ModelState.

Por ejemplo:

en Acción:

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

y para obtener el mensaje "Error 1":

ViewData.ModelState["CustomError"].Errors[0].ErrorMessage 
Cuestiones relacionadas