How to clean an @Html.TextboxFor using JavaScript?

1

I'm trying to clear the value entered in the TextBoxFor field from the following form shortly after the submit.

@BHS_Treinamento.WebApi.Models.Curso

@{
    ViewBag.Title = "Cadastrar";
}

<h1>Cadastrar</h1>

@using (Html.BeginForm(null, null, FormMethod.Post, new { @action = "/api/cursos/", onsubmit = "return submitForm()"})) {
<!--Abaixo o Ajax BeginForm-->
@*@using (Ajax.BeginForm("Cadastrar", new AjaxOptions { OnSuccess = "submitForm" })) {*@
@Html.ValidationSummary(true)


<div class="editor-label">
    @Html.LabelFor(model => model.Nome)
</div>
<div class="editor-field" >
    @Html.TextBoxFor(model => model.Nome, new { id = "modelNome" })
    @Html.ValidationMessageFor(model => model.Nome)
</div>
<br />
<p>
    <input type="submit" value="Create" class="btn btn-success"/>
</p>
}

<div>
    @Html.ActionLink("Voltar para Home", "Index", "Home")
</div>

<script type="text/javascript">

function submitForm() {
    debugger;
    if ($("#modelNome").val().replace(/^\s+|\s+$/g, "").length != 0) {
        alert("Cadastrado com sucesso: " + $("#modelNome").val());
    }
    else
        alert("Erro, campo não pode ficar vazio.");
    //$("#modelNome").val("");
}
</script>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

This way the value value is entered ok. If I take the comment from the script for the name field to receive empty ( $("#modelNome").val(""); ) the value is entered as empty too, because the form's action is onSubmit , or either before saving, the value is changed and this new value is passed to the register. I've looked in other forums that some people use @ Ajax.BeginForm to be able to use OnSuccssess , (this is commented as I tried to use), but it does not save the data but clears the screen. So I decided to look at the debugger by the browser and saw that it does not enter the submitForm function it created. I'm starting now in programming so thank you for understanding if the question level is below average.

    
asked by anonymous 23.02.2018 / 19:32

1 answer

2

To use the Ajax.BeginForm() method, the Microsof jQuery Unobtrusive Ajax plugin must be referenced in your project / file (available in NuGet ).

With the plugin referenced and the route configured properly, the operations performed can be tracked in the% developer's% tab in your browser.

Note that in the Network property of the OnSuccess class, the javascript function is responsible for performing the action after the successful registration.

    
23.02.2018 / 20:25