1

I have a html form in which I write in a text box and submit when press a button and it saves in db but I want the page not to refresh and continue with the values ​​in the text box

I have see people talking about ajax but I have never worked with ajax

    <div class="row" style="float:left; margin: 2px ">

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="col-md-3">
            <div class="form-group">
                <label>Pressão Injeção:</label> 
                <input id="id3" type="text" name="Pressão_de_Injeção" /> <br />
            </div>
        </div>

Jonathan Willcock
  • 5,012
  • 3
  • 20
  • 31
  • 1
    Check out this link for MVC ajax form submit: - [https://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor][1] – Tarun Gosain Jun 04 '19 at 11:24
  • There are so many way to achieve. If we are using razor view, we can use html.ajax helper. [https://www.tutorialspoint.com/mvc_framework/mvc_framework_ajax_support.htm](https://www.tutorialspoint.com/mvc_framework/mvc_framework_ajax_support.htm) – user2803730 Jun 04 '19 at 18:35

2 Answers2

2

Here is a quick example of an AJAX call which will POST data to an controller:

var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
  url: "Home/SaveForm",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});

request.done(function(msg) {
  console.log('success');
});

request.fail(function(jqXHR, textStatus) {
  alert( "Request failed: " + textStatus );
});

Note, that you can also pass objects to the controller by supplying them as an variable within the data object:

var menuId = $("ul.nav").first().attr("id");
var obj = {
  id: menuId,
  text: "Foo"
};
var request = $.ajax({
  url: "Home/SaveForm",
  type: "POST",
  data: {name: "Jim", object: Obj},
  dataType: "html"
});

(Code adapted from an answer by apis17.)

An introduction to AJAX, can be found here: https://www.w3schools.com/js/js_ajax_intro.asp

The only other method of performing what you required (without using AJAX) is to use a form submit and pass the data back to the HTML form once complete. You would then need to re-populate the fields (however, this will cause additional work on both submitting and re-populating, if (and/or when) new fields are adding if the future).

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
MrBritton
  • 31
  • 1
  • 5
0

You will have to take the ajax approach.

But if you don't want to do that, you can always post to the controller and return the model to the view. It will have the text you entered into the textbox.eg.

public IActionResult MyView()
        {
            return View();
        }

[HttpPost]
public IActionResult MyView(MyModel model)
            {
                return View(model);
            }

Hope this helps as an alternative.

Bradley Petersen
  • 155
  • 1
  • 10