-3

i want to make a form validation with the ajax language. Just a simple one so i can start expanding it. I have a model, controller and a view, but i don't know how to start go ahead from here.

            <form id="myForm">

            @Html.TextBoxFor(model =>model.News, new { @class = "form-control", @placeholder = "Email" })

            <input type="button" value="SignUp" class="btn-block btn-primary" id="btnSubmit"/>

        </form>
<script> 
    $(document).ready(function () {

        $("#btnSubmit").click(function () {
             debugger
            var data = $("#myForm").serialize(); 

            $.ajax({

                type: "POST",
                url: "/News/Index",
                data: data,
                success: function (response) {

                    alert("Data saved to the database");

                }

            })
        })
    })
</script>

Model :

public class News
{
    public int NewsId{ get; set; }
    public string Email { get; set; }
}

Controller:

        [HttpPost]
    public ActionResult Index(News model)
    {
        try
        {
            News newsletter= new News();
            newsletter.Email = model.Email;

            _context.News.Add(newsletter);
            _context.SaveChanges();
        }
        catch (Exception e)
        {
            throw e;
        }

        return View(model);
    }
tereško
  • 58,060
  • 25
  • 98
  • 150
See Sharp
  • 1
  • 3
  • 2
    Well, what do you want to "validate" and where do you want to validate it? That seems like where you'd start. Also note that your `catch` block is entirely superfluous and is hiding information about the exception. It would be better to just remove that try/catch entirely. – David Jan 30 '18 at 12:38
  • I want to validate the emailadres that is entered in a input textbox. It needs to be validated into the _context database and the table News. I will remove the try and catch :) – See Sharp Jan 30 '18 at 12:51
  • So you want to validate it *in the database*? Or before you save it to the database? Be specific. You can validate it in JavaScript before submitting the form, in C# after receiving the form, etc. – David Jan 30 '18 at 13:35
  • The thing is i need to use AJAX, so i'm not sure what the best solution will be with using ajax. – See Sharp Jan 30 '18 at 13:50
  • Possible duplicate of [Use ASP.NET MVC validation with jquery ajax?](https://stackoverflow.com/questions/14005773/use-asp-net-mvc-validation-with-jquery-ajax) – Steve Greene Jan 30 '18 at 14:11

3 Answers3

0

I would advise you to use BeginForm instead

@using (Html.BeginForm("Index", "News", , FormMethod.Post))
{
   @Html.TextBoxFor(model =>model.News, new { @class = "form-control", @placeholder = "Email" })

   <input type="button" value="SignUp" class="btn-block btn-primary" id="btnSubmit"/>
}

This way you won't need to use AJAX, you could post your form like a simple HTML form to your controller. Try it. Then you would be able to use server validation.

Else you could try to implement something like jQuery.validate.js to provide client validation.

Alex
  • 729
  • 2
  • 10
  • 24
  • Thanks for your answer, but i need to use AJAX for a exercise. I looked into your solution before, but it is just basically avoiding ajax. – See Sharp Jan 30 '18 at 12:52
  • No problem do you need to implement a client or server side validation? – Alex Jan 30 '18 at 13:05
  • When the emailadress has been submitted it needs to be saved to the table News in the database. _context is the variable with the database inside it. So i thought it would work with saving it like i did in the controller, but i guess i miss something in my form. – See Sharp Jan 30 '18 at 13:08
  • I'm not sure to understand, by validation do you mean to prevent posting a form with void fields for example? or simply submitting it and posting your data to the controller? – Alex Jan 30 '18 at 13:12
  • Simply submitting it and posting the data to the controller – See Sharp Jan 30 '18 at 13:15
  • If it's the latter your AJAX submission seems wrong. If you only need to send the email address, simply put your string in the data without serialization, `$.ajax({ url: "/Search/UpdateSearchData", type: "POST", data: "string" /* or $('#textboxid').val()*/, success: function (response) { if (response) toastr["warning"]("Les données n'ont pas été générées, veuillez recharger la page."); } });` – Alex Jan 30 '18 at 13:17
  • If you need to post a model I guess this can help https://stackoverflow.com/a/33947968/7424707 – Alex Jan 30 '18 at 13:18
  • Sorry for the ajax call there's a bi msitake `data: {Email: $('#textboxid').val()}` should do the work, assuming your controller takes one string argument called Email. – Alex Jan 30 '18 at 13:26
  • But the question is, how would you implement that with a textbox in a form? i am confused on that part. – See Sharp Jan 30 '18 at 13:26
  • I think you need to put `@model yourNameSpace.News` at the begining of the view – Alex Jan 30 '18 at 13:28
  • then your textbox should look like `@Html.TextBoxFor(model =>model.Email, new { @class = "form-control", @placeholder = "Email" })` – Alex Jan 30 '18 at 13:29
  • You would probably access its value with `$('#Email')`. – Alex Jan 30 '18 at 13:31
  • Alright, i made the changes but this doesn't post the data to the table yet. Is that because the form tag itself is not done? Do i have to put things in there or does something else have to change? – See Sharp Jan 30 '18 at 13:37
  • In fact the form tag does not matter in this case because AJAX does everything, you only need to get the value of the textbox whether it's in a form or not. Do you get an error message? Try to put a break point in your controller to see what's in the parameter (Your controller should be like `public ActionResult Index(string Email)`). Assuming the controller is called. – Alex Jan 30 '18 at 13:50
  • No i don't get an error message, it just doesn't pasted anything in the database. With the parameter change you did i have to change more thing in the that public functon in the controller. Not sure what to do about it. – See Sharp Jan 30 '18 at 14:02
0

You can use DataAnnotation to validate model properties

Use-> using DataAnnotationsValidations.Models;

public class News
{
    public int NewsId{ get; set; }
[Required]
    public string Email { get; set; }
}
Mayank
  • 333
  • 1
  • 5
  • 15
0
public class News
{
     public int NewsId{ get; set; }
    [Required(ErrorMessage = "Field can't be empty")]
    [DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
    public string Email{ get; set; }

}

  @Html.TextBoxFor(model =>model.Email, new { @class = "form-control", 
        @placeholder = "Email" })

        <input type="button" value="SignUp" class="btn-block btn-primary" id="btnSubmit"/>
Amal Sebastian
  • 193
  • 3
  • 19