Conditional validation depending which MVC button pushed

J Fisher 0 Reputation points
2023-09-25T13:56:00.5533333+00:00
I have a scaffolded form in MVC with two buttons, Save and Submit. I want conditional validation: Save, no validation; Submit, validation.

In the cshtml I have:

...
<td>
    @Html.EditorFor(model => model.DSCRPTN, new { htmlAttributes = new {@class = "col-md-6", autocomplete = "off", @style = "width:1000px" } })
</td>
<td>
    @Html.DropDownListFor(model => model.FUNDING_SRC1, (SelectList)ViewBag.FSRC, "<Select>", new { style = "width:125px" })
</td>
...
<div class="col-md-offset-2 col-md-10">
    <br />
    <input id="Button2Submit" type="submit" value="Submit" name="submit" class="btn btn-default" />
    <input id="Button2Save" type="submit" value="Save" name="submit" class="btn btn-default" 
    @Html.ActionLink("Cancel", "Index", null, null, new { @class = "btn btn-default" })
</div>
...

In the controller I currently have:

if (submit == "Save") {Session["SavePushed"] = true;}
if (submit == "Submit") {Session["SubmitPushed"] = true;}

Potential solutions:
1. A custom validator does not work because it is executed before the controller code is, making my passed Session variables null.
2. Passing dummy values thru the model to fool the Required=true validator does not work, since modelstate is still false with dummy values.
3. Adding a new model for two models total, one with Required=true and the other w/o Required... Has anyone tried this?
4. Client-side validation. Before I switch over to this, has anyone tried #3? Thanks.
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 1,510 Reputation points
    2023-09-25T15:40:07.54+00:00

    As far as I can tell, you are asking how to clear model state validation errors in a controller if the Save submit button was clicked.

    if(submit == "Save")
    {
        ModelState.Clear();
    }
    

    If you are trying to ignore validation errors on the client (unobtrusive), then you have to write JavaScript to catch the save button click and submit the form with JavaScript.


  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-09-25T17:00:10.0866667+00:00

    just turn off client validation for the save button:

    <input id="Button2Save" type="submit" value="Save" formnovalidate name="submit" class="btn btn-default" />
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.