When I click Submit
button in form tag, values I have collected in variables when page loaded first are getting erased. I am using In .Net Core MVC.
This is my code
public IActionResult Index(string cap)
{
var rnumber = ViewData["captcha"];
if (cap == rnumber)
{
Isvisble = "visible";
}
randnumber = RandomString(6);
ViewData["captcha"] = randnumber;
return View();
}
This is my cshtml code
<form method="get" asp-action="Index">
<div >
<h1 >Welcome</h1>
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblCapval" for="captchasym"><b>@ViewData["captcha"]</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button type="submit">Login</button>
</div>
</form>
Here when I click on submit button
, randnumber
and ViewData["captcha"]
both are null
in Index
method. How can I retain those values ?
CodePudding user response:
ViewData
itself cannot be used to send data from View to Controller. You can use Session
instead:
Controller:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISession _memorySession;
public HomeController(ILogger<HomeController> logger, IHttpContextAccessor httpContextAccessor)
{
_logger = logger;
_httpContextAccessor = httpContextAccessor;
_memorySession = _httpContextAccessor.HttpContext.Session;
}
public IActionResult Index(string cap)
{
var rnumber = _memorySession.GetString("captcha");
if (cap == rnumber)
{
Isvisble = "visible";
}
string randnumber = RandomString(6);
_memorySession.SetString("captcha", randnumber);
return View();
}
}
View:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor
@{
ViewData["Title"] = "Home Page";
}
<form method="get" asp-action="Index">
<div >
<h1 >Welcome</h1>
<label for="captcha"><b>Enter chaptcha - </b></label>
<label id="lblCapval" for="captchasym"><b>@httpContextAccessor.HttpContext.Session.GetString("captcha")</b></label>
<input id="txtCapValue" type="text" placeholder="Enter captcha" name="cap" required>
<br />
<button type="submit">Login</button>
</div>
</form>
Don't forget to register services and middleware:
builder.Services.AddSession();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
app.UseSession();
Test Result:
In addition, you need to pay attention that your Index
method will enter the RandomString
method every time, if you want to save the randnumber
, you need to add a judgment condition. For example, the RandomString
method is only entered when rnumber==null
.
You can also use input to pass ViewData
back to the controller as a string:
<input type="hidden" name="captcha" value="@ViewData["captcha"]" />
And your controller:
public IActionResult Index(string cap ,string captcha)
{
var rnumber = captcha;
}