Reyneer Leon
Reyneer Leon

Reputation: 456

How to prevent submit button going up in ASP.NET MVC?

For example I am coding my own portfolio in MVC using HTML, CSS and JS and my website is one-paged that has(in order): Home, skills, Projects, About, Contact and I have to scroll to see each section. The problem is when I click the submit button(Contact section), page refreshes and starts from the beginning and I have to scroll down again to see validations errors or if the model submitted successfully.

This is what I have:

View

<section class=" sect-container habilis">
<div class="container contac">
    <h2><img src="~/Content/images/0QLAF5.png" /></h2>
    <hr />
    @using (Html.BeginForm())
    {
        // the rest of forms code

        <button type="submit" class="btn btn-danger btn-md">Enviar</button>
    }
</div>
</section>

Controller

public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(Contact viewModel)
    {
        if (ModelState.IsValid)
        {
            _contact.Add(viewModel); // adds and saves model to database
            TempData["Message"] = "¡Su formulario se ha enviado con éxito!";
        }
        return View(viewModel);
    }

Tried this and worked but didn't work for checking erros or submitting to database:

   $(document).ready(function () {
        $("form").submit(function (e) {
            e.preventDefault();
        });
     });

Upvotes: 1

Views: 852

Answers (1)

errorau
errorau

Reputation: 2334

you can use like that

@using (Html.BeginForm("anotherAction", "anotherController", FormMethod.Post, new { id="frmRegister", @class = "form-horizontal", role = "form", target = "nulframe" }))

second you can separate on controller side like that

[HttpPost]
public void Index(Contact viewModel)
{
    if (ModelState.IsValid)
    {
       // to do  :Save 
      return RedirectToAction("SuccesfullyRegistered","Account");
      // here is redirect page  
    }
    return View(viewModel);
}

Also if you use jQuery ou can handle when u click submit button then send ajax request another controller another action

I write an example for this problem I have 2 controllers Home and Demo when I post action on Home controller İ redirect to demo controller like that

 public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        return View();
    }

    [HttpPost]
    public ActionResult About(string id)
    {
        if(id != "")
        {
            return RedirectToAction("Index", "Demo");
        }

        return View();
    }

in about page

<form method="post" action="/Home/About">
  <input type="text"  placeholder="id" name="id" class="form-control "/>
  <button class="btn btn-default">Send Post</button>

it worked for me

Upvotes: 1

Related Questions