0

I have two buttons but I'm only able to validate one. When the user clicks add and the entire form is not filled out then they get error message but if they click finish instead of giving error messages, it goes to another page but I want to give the error before going to that page. This is what I have so far for one:

@model student.Models.Student

<h2>Student Record</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Issue</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.studentNumber, htmlAttributes: new { @class = "col-md-2" })
            @Html.EditorFor(model => model.studentNumber, new { htmlAttributes = new { @readonly = "readonly", @id = "reqnum", @class = "form-control" } })
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "col-md-2" })
            @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
        </div>

        <div class="form-group">
            @Html.Label("Processed by:", htmlAttributes: new { @class = "col-md-2" })
            @Html.DropDownListFor(model => model.processedbyDetails.employeeNum, new SelectList(ViewBag.StoresReps, "Value", "Text"), new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.processedbyDetails.employeeNum, "", new { @class = "text-danger" })

        </div>

        @* -- MANY OTHER INPUTS -- *@


        <div class="form-group">
            <div class="col-md-offset-4 col-md-12">
                <input type="submit" value="Add" name="Add" class="btn btn-default" width="89" />
                <input type="button" value="Finish" name="Issue" margin="50px" onclick="location.href='@Url.Action("ViewIssue", "Issue")' " class="btn btn-default" />
                <input type="button" value="Cancel" name="Cancel" margin="50px" onclick="location.href='@Url.Action("Cancel", "Issue")' " class="btn btn-default" />
            </div>
        </div>
    </div>
}

Edit

@{
    ViewBag.Title = "Student Item";
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

<script type="text/javascript">

<script type="text/javascript">
 function onFinishClick() {
        if ($('form').valid()) {
            location.href = '@Url.Action("ViewIssue", "Issue")';
            }
            return false;
            }
</script>


<input type="button" value="Finish" name="Issue" margin="50px" onclick="onFinishClick()" class="btn btn-default" />

1 Answers1

0

You're using MVC, so just annotate your ViewModel and submit the form with the built in functionality that the framework supplies for you.

public class Student
{
    [StringLength(100)]
    [DisplayName("Student Name")]
    [Required(ErrorMessage = "Please enter a Student Name")]
    public string Name { get; set; }

    [StringLength(100)]
    [DisplayName("Student Number")]
    [Required(ErrorMessage = "Please enter a Student Number")]
    public string StudentNumber { get; set; }

    // etc...
}

Your form should also have the name of the Action you're trying to POST to...

@using (Html.BeginForm("AddOrFinish", "HomeController", FormMethod.Post, new { role = "form" }))

You can't validate against the data annotations on your viewmodel in MVC from a button that's not of type submit (well, maybe you can, but probably more work).

You should then mark both buttons as type submit, then interrogate the name of the button that was clicked once it is sent over.

    <div class="form-group">
        <div class="col-md-offset-4 col-md-12">
            <input type="submit" value="Add" name="add" class="btn btn-default" width="89" />
            <input type="submit" value="Finish" name="issue" margin="50px" class="btn btn-default" />
            <input type="button" value="Cancel" name="Cancel" margin="50px" onclick="location.href='@Url.Action("Cancel", "Issue")' " class="btn btn-default" />
        </div>
    </div>

Then in your controller, create a method with this signature. Since you have two submit buttons, the values of the button will be sent along in the request and you can interrogate it. It will look something like this...

[HttpPost]
public ActionResult AddOrFinish(Student model, string add, string issue)
{
    if (!ModelState.IsValid)
    {
        return RedirectToAction("PageImOnNow", model);
    }

    if (!string.IsNullOrEmpty(add))
    {
        // do your add logic
        // redirect to some page when user clicks "Add"
        return RedirectToAction("WhateverPageYouWant");
    }
    else
    {
        // do your finish logic
        // redirect to ViewIssue page when user clicks "Finish"
        return RedirectToAction("ViewIssue");
    }
}

More information here -

Handling multiple submit buttons on a form in MVC

Best Practices for ViewModel validation in MVC

ragerory
  • 1,360
  • 1
  • 8
  • 27
  • it is redirecting to another page which doesn't exist, where do I change it to the correct url. when I add it suppose to remain on the page but when it is finish it redirected –  Sep 06 '17 at 14:06
  • @Jane Well, look at your controller names and views that are in there. I assumed `HomeController` and `ViewIssue`, but that is an example, you need to update that to the views and controllers that are actually yours. – ragerory Sep 06 '17 at 14:08
  • How would I allow it to be one page when it is add and when it finish redirects. –  Sep 06 '17 at 14:13
  • @Jane That's in my example. When it is Finish it redirects, if it is Add, you can have it go elsewhere - see edit. – ragerory Sep 06 '17 at 14:15
  • I have that but some how it is still redirecting to the other page, not sure if it is because of this AddOrFinish", "HomeController", FormMethod.Post, new { role = "form" –  Sep 06 '17 at 14:17
  • @Jane did you remove your javascript stuff? Because you don't need it anymore. If you added the AddOrFinish method, then it will go to that `ActionResult` when you submit your form and go through that method. Are you in your HomeController as well? If you're in a different controller, then you'll need to change that in the `using` statement to reflect it as such. Also, did you change your buttons? The two submits should not have an onclick event anymore. – ragerory Sep 06 '17 at 14:19
  • yes I did remove it. and I have make the necessary changes –  Sep 06 '17 at 14:22
  • @Jane So when you say it's redirecting to a different page what does that mean? What `Controller` did you add `AddOrFinish` to? If you put a breakpoint in `AddOrFinish` does it hit? This is a very common practice and I have an example working with what I have below. – ragerory Sep 06 '17 at 14:25
  • It is in a controller called Issue, I have made some changes and the add worked but when I click finish nothing happens –  Sep 06 '17 at 14:27
  • @Jane Again, if you put a breakpoint in `AddOrFinish` does it get hit? – ragerory Sep 06 '17 at 14:28
  • @Jane did you change the `using` statement to be `Issue` instead of `HomeController`? – ragerory Sep 06 '17 at 14:29
  • yes I did..when I remove this "AddOrFinish", "HomeController", FormMethod.Post, new { role = "form" from using, the data is added but click finish it clears out data. yes it does hit the action –  Sep 06 '17 at 14:32
  • @Jane you have a contradicting item here. You say you changed "HomeController" to "Issue" but the last comment says you removed "AddoOrFinish", "HomeController" - that is wrong. If you hit a breakpoint in AddOrFinish, you need to step thru the code and find out why Finish isn't giving you the desired result, because you have all the tools now and Add is doing what you want, so you know it's working, and now just a bug in your Finish logic. If you remove that `using` statement, your controller will not get hit. – ragerory Sep 06 '17 at 14:34
  • This is what I have @using (Html.BeginForm("ViewIssue", "Issue", FormMethod.Post, new { role = "form" })) but that was just sending it to view issue page whether i clicked add or finish. But when I removed it the data is added but when finished it clicked it is not redirected –  Sep 06 '17 at 14:36
  • @Jane why do you have it go to `ViewIssue`? Literally create the `AddOrFinish` method into your controller and change your `using` statement to use that. In that method, it will determine if you hit add or finish, and redirect the way you want. Look at the code. When you click submit the value of the button that was clicked is sent back to that method so you know which is clicked. – ragerory Sep 06 '17 at 14:38
  • but it gives an error when I use AddOrFinish, server error, the resource cannot be found. –  Sep 06 '17 at 14:46
  • @Jane you're making it hard to help. What error are you getting? – ragerory Sep 06 '17 at 14:47
  • I'm sorry I'm making this hard, but i'm not use to this. –  Sep 06 '17 at 14:50
  • @Jane lets take a step back. Copy and paste your `using` statement as you have it now. – ragerory Sep 06 '17 at 14:51
  • @using (Html.BeginForm("ViewIssue", "Issue", FormMethod.Post, new { role = "form" })) –  Sep 06 '17 at 14:55
  • @Jane what does your `ViewIssue` method look like? – ragerory Sep 06 '17 at 14:56
  • public ActionResult ViewIssue() { //returns the details to the session variable to the view Receipt View return View(getIssue); } –  Sep 06 '17 at 15:02
  • @Jane you literally did nothing that I showed in the code above other than add the `using` statement. In your `Issue` controller, add the entire `AddOrFinish` method. Add that method to your controller. THEN change your `using` statement to be "AddOrFinish" INSTEAD of "ViewIssue" - keep the controller the same. That will WORK. If you are getting an error I can send you the project that proves it. – ragerory Sep 06 '17 at 15:04
  • What do you mean I did nothing, I have added ADDORFINISH Method to the controller, changed what you stated. –  Sep 06 '17 at 15:06
  • If you changed your `using` statement to `AddOrFinish` and you added that method to the `IssueController` then it will work 100%. If it's saying resource not found, that means it can't find that method. What is your email? I've copied and pasted this code into a solution and it works the way you're wanting it to. I will gladly send it over. – ragerory Sep 06 '17 at 15:15
  • you could use pastebin or .net fiddle, –  Sep 06 '17 at 15:21
  • Say for example after the user as clicked add and the data is added, then click finish it redirects them to view issue but if nothing wasn't added it gives an error/alert. how would I do that –  Sep 06 '17 at 15:32
  • @Jane the example I posted above does all of that. If you click on Add, it hits the `AddOrFinish` `ActionResult`. If the requirements on the model do not validate, it will execute the `if (!ModelState.Valid)` block and return a view. Above, we just have `return View(),` but you may actually need `return RedirectToAction("NameOfPageYourCurrentlyOnGoesHere", model)` instead. – ragerory Sep 06 '17 at 15:41
  • I was just saying that because the add and finish is beside each other but when the data is added it goes in a table below, so I was thinking to remove the finish and put it below the table, then check if any thing was entered redirect them to the other page or give an error. –  Sep 06 '17 at 15:45
  • I understand what you are saying, but i'm trying to make as best user-friendly as possible. –  Sep 06 '17 at 15:45
  • What I'm saying has nothing to do with user experience, and is the proper way to handle what you're asking to achieve. I'm not sure what code you've added in order for this not to work the way I proposed, but I have a working solution with the code above verbatim that you can see here: https://www.dropbox.com/s/2oci4hpjd3d2qwq/WebApplication3.zip?dl=0 – ragerory Sep 06 '17 at 15:49
  • wasn't talking about user experience, for it to be user friendly. It is ok now, but i'm saying instead of the errors for the different fields when the user click finish, how can I give one error that says they didn't add item. –  Sep 06 '17 at 16:07