Nuno Ferreira
Nuno Ferreira

Reputation: 11

How do I submit a form, but my text boxes preserve their values in asp.net Razor pages

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>

Upvotes: 1

Views: 642

Answers (2)

MrBritton
MrBritton

Reputation: 31

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).

Upvotes: 2

Bradley Petersen
Bradley Petersen

Reputation: 155

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.

Upvotes: 0

Related Questions