manabu
manabu

Reputation: 471

How can I display the correct value?

I'm using ASP.NET MVC 5.2.7

My browser is Google Chrome 84.0.4147.89

Here's my program.

view

<form action="/Tabulations" method="post">
    <div>
        <input type="text" id="condition1" name="condition1" value="@ViewBag.Condition1.ToString()" required />
        <input type="submit" formaction="dummy" value="submit" />
    </div>
</form>
<p>[email protected]()</p>

controller

using System;
using System.Web.Mvc;

namespace Controllers
{
    public class TabulationsController : Controller
    {
        public ActionResult dummy(Nullable<int> condition1)
        {
            if (condition1.HasValue)
                ViewBag.Condition1 = condition1.Value;
            else
                ViewBag.Condition1 = 0;
            return View("dummy");
        }

    }
}

This is what the initial page looks like.

initial page

This is what it looks like when enter 1 and submit it.

enter image description here

When I click on the browser's back button, the initial page should be displayed.

The value shown in the p tag is back to 0. However, the value shown in the input tag is remains 1.

enter image description here

I look at the source of the page, the value in the input tag is 0.

enter image description here

Why is 1 displayed as the value of the input tag?

How can I display the correct value?

Upvotes: 0

Views: 27

Answers (1)

Rutuja
Rutuja

Reputation: 460

$(document).ready(function(){
CheckCondition();
$('#form').submit(function(e){
e.preventDefault();
  CheckCondition();
});

$('#condition1').change(function(){
CheckCondition();
});
});

function CheckCondition(){
  var conditionText = $('#condition1').val();
    
    if(conditionText != null && conditionText != undefined && conditionText != "")
    {
        $('#condition').html("Condition 1 = " + conditionText);
    }
    else
    {$('#condition1').val(0);
       $('#condition').html("Condition 1 = " + 0);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/Tabulations" method="post" id="form">
    <div>
        <input type="text" id="condition1" name="condition1" value="" required />
        <input type="submit" formaction="dummy" value="submit" />
    </div>
</form>
 <p id="condition"></p>

It is showing 1 because value is being changed at server side and you are just doing browser back which only executes client side code. You added code in form submit so, if you add code in ajax or in jquery ready function then it will work fine.

Upvotes: 1

Related Questions