ModelState.AddModelError is not being displayed inside my view

后端 未结 3 1433
鱼传尺愫
鱼传尺愫 2020-12-13 08:50

I have the following view,, which create 10 ajax.beginform ,, But the problem that i am facing is that incase an error occurs during the creation of the object then the Mode

相关标签:
3条回答
  • 2020-12-13 09:11


    I would urge you to change your try{ } catch(){ }

    And first check if there exists a visit for the given id and if so simply returns the model with the added model error

        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
    

    Change your AddModelError To

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

    And in your view simply add a

    @Html.ValidationMessage("CustomError")
    

    Then when you return your model the error will be shown where you have placed the @Html.ValidationMessage ...

    0 讨论(0)
  • 2020-12-13 09:24

    You can use from ViewData dictionary in View to access ModelState data.

    For example:

    in Action:

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

    and to get "Error 1" message:

    ViewData.ModelState["CustomError"].Errors[0].ErrorMessage
    
    0 讨论(0)
  • 2020-12-13 09:28

    @Html.ValidationSummary(true) shows only the error message about model's propertys, if you want to show also the added message, added with

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

    you need to set @Html.ValidationSummary(false) If you need to display the validation's message near your input fields you need to set @Html.ValidationSummary(true) and to follow the steps suggested by Syneryx

    0 讨论(0)
提交回复
热议问题