I try to change the value of an input button after it was clicked. The button itself is an submit button, and the controller is getting back to the page by RedirectToAction. My problem is, that I can change the value of the button, but this new value is only shown for a millisecond before it is set back to its original value. Is the page reloaded after the script fired? Or why is the button value set back after the script fired?
Here is my code: The button:
@using (Html.BeginForm("StartNewM2OLIEProcess", "Patient", new { label = Model.PatientID }, FormMethod.Post))
{
<input type="submit" id="btnStartProcess" value="M²OLIE Prozess starten" class="btn btn-primary" />
}
The Script
@section Scripts{
<script type="text/javascript">
$("#btnStartProcess").on('click', function () {
var self = $(this);
var errorMsg = '@errorMsg';
if (errorMsg == '') {
//self.attr('M2OLIE Prozess starten', 'Prozess gestartet');
self.val('Prozess läuft...');
}
else {
self.val("M²OLIE Prozess starten");
}
});
</script>
<script type="text/javascript">
var message = '@message';
if(message){
alert(message);
}
</script>
}
So the scripts are correctly fired, that I could test with the debugger. And I can also see the value of the button changing during debugging, but as soon as the script ends, the value changes back to the value that is defined in the Html form. What is happening here?
When the first click, the jQuery event is executed, then the page is sent to the action. You either have to post the page or manage the click event.
test this code with your script
$("form").submit(function (e) {
e.preventDefault();
});
I will give you an example to see how the changes after the form post.
In Controller
[HttpGet]
public ActionResult StartNewM2OLIEProcess()
{
return View();
}
[HttpPost]
public ActionResult StartNewM2OLIEProcess(string myText)
{
ViewBag.ButtonText = myText;
return View();
}
In View
@{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("StartNewM2OLIEProcess", "Home", FormMethod.Post))
{
string buttonValue = "M²OLIE Prozess starten";
if (!string.IsNullOrEmpty(ViewBag.ButtonText))
{
buttonValue = ViewBag.ButtonText;
}
<input type="text" id="myText" name="myText" />
<input type="submit" id="btnStartProcess" value="@buttonValue" class="btn btn-primary" />
}
<div id="myDiv" style="width:300px;height:50px;background:#FF5511;color:white;text-align:center;font-weight:bold;"></div>
@section scripts{
<script>
var result = '@(ViewBag.ButtonText)';
if (result != null) {
document.getElementById("myDiv").innerText = result;
}
</script>
}