Form submit returns a blank page - asp.net-core

I'm trying to do a basic login with a form in my .cshtml file that goes like this:
<form method="post">
<input type="text" name="nombre"/>
<input type="password" name="contra"/>
<input type="submit" value="login" />
</form>
And checking it in the .cshtml.cs with his method where I compare each input with a value:
public void OnPost()
{
var Username = Request.Form["nombre"];
var Password = Request.Form["contra"];
if (Username.Equals("jsplata") && Password.Equals("1234"))
{
RedirectToPage("https://www.google.com/");
}
else
{
RedirectToPage("https://www.stackoverflow.com/");
}
}
When I press the submit button it returns a blank page, I don't know what might be wrong about this.

You can try to use below codes :
public IActionResult OnPost()
{
var Username = Request.Form["nombre"];
var Password = Request.Form["contra"];
if (Username.Equals("jsplata") && Password.Equals("1234"))
{
return Redirect("https://www.google.com/");
}
else
{
return Redirect("https://www.stackoverflow.com/");
}
}

Related

Properties set to null when OnPost handler is called in razor page

I have a page with 2 buttons each one with their handler methods (OnPostAsync and OnPostResend) and 2 properties (LoginType and DocumentNumber) when OnPostAsync is called, properties have their values and the method works as expected but when the second button is clicked and OnPostResend is called properties are set to null. Why is this happenning and how can I prevent it?
This is the .cshtml file:
#page
#model SATCloudWebApp.Areas.Identity.Pages.Account.EnterOtpModel
#{
ViewData["Title"] = $"Ingrese el código de confirmación";
string device = TempData["PhoneNumber"]
}
}
<h2>#ViewData["Title"]</h2>
<div class="row">
<div class="col-md-6">
<h4>Por favor digite el código enviado a su #device. </h4>
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.OtpCode"></label>
<input asp-for="Input.OtpCode" class="form-control" />
<span asp-validation-for="Input.OtpCode" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-info">Siguiente</button>
</form>
<href>
<form asp-page-handler="resend" method="post">
<button id="resendToken" type="submit" class="btn btn-dark">Reenviar código</button>
</form>
</href>
</div>
</div>
This is the page model:
namespace Name
{
[AllowAnonymous]
public class EnterOtpModel : PageModel
{
// constructor goes here ...
[BindProperty]
public string LoginType { get; set; }
[BindProperty]
public string DocumentNumber { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required(ErrorMessage = "Ingrese el código enviado.")]
[Display(Name = "Código de inicio de sesión")]
public string OtpCode { get; set; }
}
public IActionResult OnGet(string loginType, string documentNumber)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToPage("~/LoginWithOtp");
}
else
{
LoginType = loginType;
List<SATCloudUser> _users = new List<SATCloudUser>();
_users = _userManager.Users.Where(x => x.DocumentNumber == documentNumber).ToList();
SATCloudUser _satUser = _users[0];
TempData["Username"] = _satUser.Email;
TempData["PhoneNumber"] = _satUser.PhoneNumber;
return Page();
}
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
List<SATCloudUser> _users = new List<SATCloudUser>();
_users = _userManager.Users.Where(x => x.DocumentNumber == DocumentNumber).ToList();
SATCloudUser _satUser = _users[0];
if (ModelState.IsValid)
{
var result = await _userManager.VerifyTwoFactorTokenAsync(_satUser, "Email", Input.OtpCode);
if (result)
{
returnUrl = returnUrl ?? Url.Content("~/Home/Index");
var auth = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);
var authenticationMethod = auth?.Principal?.FindFirstValue(ClaimTypes.AuthenticationMethod);
await _signInManager.SignInAsync(_satUser, false, authenticationMethod);
return LocalRedirect(returnUrl);
}
else
{
TempData["Username"] = _satUser.Email;
TempData["PhoneNumber"] = _satUser.PhoneNumber;
TempData["messageEnterOtp"] = "InvalidToken";
return Page();
}
}
else
{
return Page();
}
}
public async void OnPostResendAsync()
{
List<SATCloudUser> _users = new List<SATCloudUser>();
_users = _userManager.Users.Where(x => x.DocumentNumber == DocumentNumber).ToList();
SATCloudUser _satUser = _users[0];
var token = await _userManager.GenerateTwoFactorTokenAsync(_satUser, "Email");
if(LoginType == "sms")
{
AlertsManager _alertManager = new AlertsManager();
string phoneNumber = "+57" + _satUser.PhoneNumber;
string message = $"Código de inicio de sesión en Better Together SE: {token}. Por favor no comparta este código.";
await _alertManager.SendTextMessageAsync(phoneNumber, message);
}
else if(LoginType == "email")
{
EmailManager _emailManager = new EmailManager();
await _emailManager.NewTokenEmail(_satUser.Email, token);
}
}
}
}
A new instance of the EnterOtpModel class is created for each request. So the state of its properties is not preserved between different requests. You can add hidden input elements inside the resend form so that LoginType and DocumentNumber are re-sent again to the EnterOtpModel.
<form asp-page-handler="resend" method="post">
<input type="hidden" asp-for="LoginType" />
<input type="hidden" asp-for="DocumentNumber" />
<button id="resendToken" type="submit" class="btn btn-dark">Reenviar código</button>
</form>

Is there a way for Code Block feature to keep line breaks in CKEditor5 with ASP.Net Core?

I am making a bulletin board system using CKEditor. Most of the features work just fine, but when editing an existing post, the all line breaks in the text are removed from the code block.
Image of create a post
Image of edit a post
Image of part of the response source
I googled as much as possible to solve this problem, but the methods I found were to no avail, so I removed it from the code again.
It seems that line breaks are removed while processing the source internally in CKEditor5, is there any way?
Replace all line breaks with <br /> tags.
Add /\r|\n/g to protectedSource
The following is the view file for that feature.
#model BBSArticleWriteView
#{
// Action name of the current view
var thisActionString = #ViewContext.RouteData.Values["action"].ToString();
if (Model.ArticleId == null)
ViewData["Title"] = "Writing";
else
ViewData["Title"] = "Editing";
}
<p class="page-header">#ViewData["Title"]</p>
<form asp-action="#thisActionString" id="editor-form">
<input asp-for="ArticleId" value="#Model.ArticleId" hidden />
<div>
<input asp-for="Title" required placeholder="Please enter a title." class="form-control w-100 mb-2" />
</div>
<div>
<textarea name="Contents" id="editor">
#Html.Raw(Model.Contents)
</textarea>
</div>
<div>
<input class="btn btn-sm btn-primary" type="submit" value="Save" onsubmit="Editor.submit()" />
<button class="btn btn-sm btn-primary" type="button" href="##" onclick="history.back()">Back</button>
</div>
</form>
<style>
.ck-editor__editable_inline {
min-height: 400px;
}
</style>
#section Scripts {
<script src="~/lib/ckeditor5/ckeditor.js" asp-append-version="true"></script>
<script>
class Editor{
static submit() {
return true;
}
}
ClassicEditor
.create(document.querySelector('#editor'),
{
simpleUpload:{
uploadUrl: "#Url.Action(nameof(CreatorFront.Controllers.FileController.Upload), "File")",
withCredentials: true
},
protectedSource:[
/\r|\n/g
]
})
.catch(error => {
console.error(error);
});
</script>
}
And here is the controller action that puts data into the view model.
[HttpGet]
public async Task<IActionResult> BBSEdit(int id)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
if(user == null)
{
return RedirectToAction("Index", "Home");
}
var article = _cContext.BBSArticle.First(a => a.ArticleId == id);
if(article == null)
{
return RedirectToAction(nameof(BBSList));
}
if(user.Id != article.UserId)
{
return RedirectToAction(nameof(BBSList));
}
var model = new BBSArticleWriteView();
CopyProperties(model, article);
return View(nameof(BBSWrite), model);
}
The following is a function that puts content data in DB.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> BBSWrite(BBSArticleWriteView article)
{
if(ModelState.IsValid)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
if(user == null)
{
RedirectToAction("Index", "Home");
}
// XSS attacks prevent
article.Contents = _htmlSanitizer.Sanitize(article.Contents);
var currentDateTime = DateTime.Now;
CreatorLib.Models.BBS.BBSArticle data = new CreatorLib.Models.BBS.BBSArticle()
{
ArticleId = _cContext.BBSArticle.Max(a => a.ArticleId) + 1,
MainCategory = article.MainCategory,
SubCategory = article.SubCategory,
UserId = user.Id,
Title = article.Title,
Contents = article.Contents,
Status = CreatorLib.Models.BBS.ArticleStatus.A,
IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
RegisteredTime = currentDateTime,
LastUpdatedTime = currentDateTime,
HasMedia = article.HasMedia
};
_cContext.BBSArticle.Add(data);
await _cContext.SaveChangesAsync();
return RedirectToAction(nameof(BBSList));
}
return View(article);
}
Here, it is confirmed that HtmlSanitizer has absolutely no impact on this issue.
In DB, line breaks are fully preserved.

Cannot update user Identity Role from list in razor page

I have a razor page which shows checkbox of Roles. The Roles owned by the selected user will be checked on page load. What I'm trying to do is, I want to be able to edit the roles for the selected user. But when I click update, it doesn't update.
Here is the razor page:
<EditForm Model="#RoleDto" OnValidSubmit="#EditRole">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="card">
<div class="card-header">
<h2>Manage User Roles</h2>
Add/Remove Roles for User / #UserFullname
</div>
<div class="card-body">
#for (int i = 0; i < numOfRoles; i++)
{
<div class="form-check m-1">
<input type="hidden" value="#RoleListModel[i].Id" />
<input type="hidden" value="#RoleListModel[i].Name" />
<input type="checkbox" checked="#RoleListModel[i].Selected" /> #RoleListModel[i].Name
</div>
}
</div>
</div>
<button type="submit" class="btn btn-success btn-block">
Confirm
</button>
#code {
ApplicationRoleDto RoleDto = new ApplicationRoleDto();
private List<ApplicationRoleDto> RoleListModel;
[Parameter] public string Id { get; set; }
[Parameter] public ApplicationUserDto UserDto { get; set; }
[Parameter] public string UserFullname { get; set; }
[Parameter] public int numOfRoles { get; set; }
protected async override Task OnParametersSetAsync()
{
UserDto = await _client.GetFromJsonAsync<ApplicationUserDto>($"api/userroles/{Id}");
UserFullname = UserDto.FullName;
RoleListModel = await _client.GetFromJsonAsync<List<ApplicationRoleDto>>($"api/rolemanager/{Id}");
numOfRoles = RoleListModel.Count();
}
async Task EditRole()
{
await _client.PostAsJsonAsync($"api/rolemanager/{Id}", RoleListModel);
_navManager.NavigateTo($"/userroles/");
}
}
and here is the controller:
[HttpPost]
public async Task<IActionResult> Manage(List<ApplicationRoleDto> model, string Id)
{
var user = await _userManager.FindByIdAsync(Id);
if (user == null)
{
NotFound();
}
var roles = await _userManager.GetRolesAsync(user);
var result = await _userManager.RemoveFromRolesAsync(user, roles);
if (!result.Succeeded)
{
Console.WriteLine("Cannot remove user existing roles");
return NotFound();
}
result = await _userManager.AddToRolesAsync(user, model.Where(x => x.Selected).Select(y => y.Name));
if (!result.Succeeded)
{
Console.WriteLine("Cannot add selected roles to user");
return NotFound();
}
return NoContent();
}
Did I miss anything here?

Adding İtems in Shopping cart

I've been working on my shopping cart program, but I keep having problems with adding an item to the shopping cart
here is my code;
HomeController class
[HttpPost]
public ActionResult AddToBasket(int id)
{
var basketJson = HttpContext.Session.GetString(SESSION_KEY);
List<SepetProduct> sepet;
if (basketJson == null)
{
sepet = new List<SepetProduct>();
}
else
{
sepet = JsonSerializer.Deserialize<List<SepetProduct>>(basketJson);
}
if (sepet.Any(x=> x.id == id))
{
sepet.Single(x => x.id == id).Toplam++;
}
else
{
sepet.Add(new SepetProduct { id = id, Toplam = 1 });
}
basketJson = JsonSerializer.Serialize(sepet);
HttpContext.Session.SetString(SESSION_KEY, basketJson);
return Json(new { status = true, Msg = "Ürün Sepete Eklendi", Data = sepet });
}
'''
and here is my Button action code
<form action="#Url.Action("addToBasket","Home")" method="post" enctype="multipart/form-data">
<input type="hidden" name="Id" value="#urun.UrunId" />
<button type="submit" class="btn btn-dark">
<span class="fa fa-shopping-cart"></span>Sepete ekle
</button>
</form>
The problem is that, when ı press to "sepete ekle" button, item was added to cart, but it directs us to a new page called "https://localhost:44302/Home/addToBasket"
and show us those data
'''
status true
msg "Ürün Sepete Eklendi"
data
0
id 2
toplam 1
'''
I would like to when ı press to 'sepete ekle ' button, the page remains the same, but the product is added to the basket. it just shows us a message saying added.
How can ı do that. thank you for interesting and helping
You can try to use ajax to replace form post.Here is a working demo:
TestBasket.cshtml(I use value="1" to test.And add id="Id" to hidden input.Also,I need to change the type of button,so that when click it,it will not submit form,it will go to submitData() function.):
<form action="#Url.Action("addToBasket","Home")" method="post" enctype="multipart/form-data">
<input type="hidden" id="Id" name="Id" value="1" />
<button type="button" onclick="submitData()" class="btn btn-dark">
<span class="fa fa-shopping-cart"></span>Sepete ekle
</button>
</form>
<script>
function submitData() {
$.ajax({
type: "POST",
url: '#Url.Action("addToBasket","Home")',
data: { "id": $("#Id").val() }
}).done(function (data) {
console.log(data.msg);
});
}
</script>
HomeController:
public IActionResult TestBasket()
{
return View();
}
[HttpPost]
public ActionResult AddToBasket(int id)
{
return Json(new { status = true, Msg = "Ürün Sepete Eklendi", Data = new List<SepetProduct>() });
}
result:

Pass value from one controller to another in ASP.NET Core MVC

How can I pass a dropdown selected value from my view to a controller then to different controller? I have a home page and an about page. On the home page the user selects an item from the dropdown, then they click on a button that navigates them to another page that has the same dropdown. My goal is to have the dropdown prepopulated on the about page based on what they selected on the home page.
My problem is that I am doing the navigation in my home page controller, so I am not getting the value of the selected value because it is not a post just a get. My variable "string countryDDL" in my home controller is null.
I am currently using TempData to pass the value, however, I am open to other options (viewbag, session state, etc). Thank you for your time.
Home page view:
<form method="post" asp-controller="Home" asp-action="Index" role="form">
<div class="form-group">
<label>Country Dropdown:</label>
<select name="countryDDL" asp-items="#(new SelectList(ViewBag.message, "ID", "CountryName"))"></select>
</div>
</form>
<a asp-action="AboutPage" asp-controller="Home">About Page</a>
Home Controller:
public void CountryDDL()
{
List<CountryModel> countryName = new List<CountryModel>();
countryName = (from b in _context.CountryModel select b).ToList();
countryName.Insert(0, new CountryModel { ID = 0, CountryName = "" });
ViewBag.message = countryName;
}
[HttpGet("[action]")]
public IActionResult AboutPage()
{
string countryDDL = HttpContext.Request.Form["countryDDL"];
int intCountry = Convert.ToInt32(countryDDL);
CountryModel data = new CountryModel()
{
ID = intCountry,
CountryName = "",
};
TempData["myData"] = data;
return RedirectToAction("Index", "AboutPage");
}
My Book Page Controller:
[HttpGet("[action]")]
[Route("/Index")]
public async Task<IActionResult> Index()
{
//get values from Home controller
CountryModel data = TempData["myData"] as CountryModel;
return View();
}
Firstly,your code makes a mistake that you could not pass TempData["myData"] redirect to another controller action with the following error message.That is because TempData uses Session, which itself uses IDistributedCache. IDistributedCache doesn't have the capability to accept objects or to serialize objects:
InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type
Here is the whole working demo:
Home/Index.cshtml:
<form method="post" asp-controller="Home" asp-action="Index" role="form">
<div class="form-group">
<label>Country Dropdown:</label>
<select id="sel" name="countryDDL" asp-items="#(new SelectList(ViewBag.message, "ID", "CountryName"))"></select>
</div>
</form>
<a asp-action="AboutPage" asp-controller="Home" >About Page</a>
#section Scripts{
<script>
$("a").click(function () {
var selectItem = $('#sel').find(":selected").val();
var href = $(this).attr('href');
if (href) {
href +="?countryDDL="+selectItem;
$(this).attr('href', href);
console.log(href);
}
});
</script>
}
HomeController:
public class HomeController : Controller
{
private readonly MvcProj3_1Context _context;
public HomeController(MvcProj3_1Context context)
{
_context = context;
}
public IActionResult Index()
{
CountryDDL();
return View();
}
public void CountryDDL()
{
List<CountryModel> countryName = new List<CountryModel>();
countryName = (from b in _context.CountryModel select b).ToList();
countryName.Insert(0, new CountryModel { ID = 0, CountryName = "" });
ViewBag.message = countryName;
}
[HttpGet]
public IActionResult AboutPage(string countryDDL)
{
int intCountry = Convert.ToInt32(countryDDL);
List<CountryModel> data = new List<CountryModel>()
{
new CountryModel()
{
ID = intCountry,
CountryName = "asd",
}
};
TempData["myData"] = JsonSerializer.Serialize(data);
return RedirectToAction("Index", "AboutPage");
}
}
AboutPage/Index.cshtml:
<form>
<div class="form-group">
<label>Country Dropdown:</label>
<select id="sel" name="countryDDL" asp-items="#(new SelectList(ViewBag.message, "ID", "CountryName"))"></select>
</div>
</form>
AboutPageController:
public class AboutPageController : Controller
{
[HttpGet]
public async Task<IActionResult> Index()
{
//get values from Home controller
ViewBag.message = JsonSerializer.Deserialize<List<CountryModel>>(TempData["myData"] as string);
return View();
}
}
Result:
Update
You could get the data like below:
[HttpGet]
public IActionResult AboutPage(string countryDDL)
{
int intCountry = Convert.ToInt32(countryDDL);
//change this line...
var data = _context.CountryModel.Where(c => c.ID == intCountry).ToList();
TempData["myData"] = JsonSerializer.Serialize(data);
return RedirectToAction("Index", "AboutPage");
}
1-you can use form to navigate and submit it with get to about page:
<form method="get" asp-controller="Home" asp-action="AboutPage" role="form">
<div class="form-group">
<label>Country Dropdown:</label>
<select name="countryDDL" asp-items="#(new SelectList(ViewBag.message, "ID", "CountryName"))"></select>
</div>
<button type="submit">About Page</button>
</form>
2-you can use jquery like below:
a: change a tag like this:
About Page
b: and select like below:(set "onChange" event)
<select onchange="$('#a_about').prop('href','/Home/AboutPage?countryDDL='+$(this).val())" name="countryDDL" asp-items="#(new SelectList(ViewBag.message, "ID", "CountryName"))" ></select>