ASP.NET MVC Redirect with Form inside IFrame - html

I am developing a SharePoint app that is using an ASP.Net MVC web application. The web application is launched inside an iframe in SharePoint.
I have a form that I use to store information related to a project. Different actions are possible on this form:
Submit form with no error: the form is redirected to the homepage of my project. For that I am using.:
Html.BeginForm(.., FormMethod.Post, new { **#target="_top**", #class = "form-horizontal" })
As you can see i redirect my form to the target _top to be able to go back to my homepage.
Cancel form: the form is cancelled and i am redirected to the homepage of my project. For that I am using also a link with the target _top:
Cancel:
Everything is working for this case
Submit form but error in the post method:
now let's imagine that i submit my form but i have some error during processing. What I would like to do is to display again the form inside my frame in my page with the validation error present on the top of the form.
The problem is explain above, my form has the target set to top, the validation errors are displayed on the top windows and not in my frame. So it is like that I am redirected to a new page.
Here is the code my post action:
if (!ModelState.IsValid)
{
return View("Edit", KeyFiguresHelper.BuildKeyFiguresEditViewModel(keyFigure, agencies));
}
var keyFiguresDTO = KeyFiguresHelper.ExtractKeyFiguresFromModel(model, agencies);
var errorCode = _projectService.EditProjectKeyFigures(keyFiguresDTO);
if (errorCode == ErrorCode.NO_ERROR)
{
return Redirect(keyFigure.ProjectUrl);
}
ModelState.AddModelError("", _errorMessageFactoryService.Create(errorCode));
return View("Edit", KeyFiguresHelper.BuildKeyFiguresEditViewModel(keyFigure, agencies));
Is it possible to redirect a page with the target "_top" if the post action is running well and if I have any errors to redirect to the same page with the target "_self" ?
Thank you very much for your help

Related

How can I pass a parameter to a GET web request without it being visible in the URL?

I am building a web application Java Spring MVC, JSPs, and jQuery.
I have a URL like this:
http://myserver/myapp/showuser/55
Which shows the "view user" page (for user id '55').
I also have an "edit user" page and after successful edit, I redirect to the "view user" page by going here:
http://myserver/myapp/showuser/55?successMsg=Successfully edited User.
The "success message" is parsed from the URL parameters and displayed on the screen.
It works well, but ...
QUESTION: How can I pass the "successMsg" value to the GET without making it part of the URL itself?
You can use btoa() and atob() to convert to and from base64 encoding.
For Plain JavaScript Web solution:
You can use History pushState method to do that.
History's state is similar to params but it is hidden from the URL.
To do that, simply:
const state = { successMsg: 'Successfully edited User'};
const title = '';
const url = 'myserver/myapp/showuser/';
history.pushState(state, title, url);
In your Show User page, access the state like
console.log(history.state) // { successMsg: 'Successfully edited User'}

ionic how to call a function in dynamic html from a database

I have a text message that my ionic app retrieves from an api that has an anchor link which needs to redirect to another page when tapped.
The html from the api is:
Tap Here
The ionic function is:
goToOtherPage(): void {
this.navCtrl.push(OtherPage);
}
I have tried:
<a onclick="goToOtherPage()">Tap Here</a>
and
Tap Here
but the first two give the message:
goToOtherPage is not defined
and the last one does nothing.
Does anyone know how I can trigger a function from dynamically retrieved html?
This will not work due to the DomSantizer that sanitizes unsafe html. I recommend retrieving the different parts of the message (eg. using JSON) and generating the page link and message via your page/component.

How can I validate on the client if I use MVC validation but posting a JSON object?

I'm developing a ASP.NET Core web application where I'm using DataAnnotations to decorate my view model with validation attributes. When I open a detail page with my inputs, I see that Core added the HTML5 validation attributes to the rendered HTML (i.e. data-val="true").
However, I wrote custom client-side code when the user clicks on the Save button like this:
$(document).on("click", "#SaveAsset", function (event) {
event.preventDefault();
Asset.Save();
});
I also have a Save function defined like this:
window.Asset.Save = function () {
var postData = {
'Id': $("#Id").val(),
'SerialNumber': $("#SerialNumber").val(),
'PartNumber': $("#PartNumber").val(),
'assetTypeId': $("#AssetTypeId").val()
};
$.post('/Asset/SaveAsset', postData);
}
I need to validate on the client side first before calling $.post but I'm confused about how to do it. Microsoft shows that the unobtrusive javascript works automatically when you use it with forms. But I'm not using the HTML form element to submit my page. So how can I trigger the HTML5 validation attributes?
I added the links to jquery.validate.js and jquery.validate.unobtrusive.js. Right now, if I click the Save button the data is sent to the server and the controller checks the ModelState. But it shouldn't even be sending anything to the server. The client should stop the validation.
Should I even stop doing it this way? For example, creating my postData JSON object by getting the val() of each input.
Should I use the form element? I stopped using it because my page has hundreds of inputs so I was worried I would have problems. This way, I have control over each input.
Use a javascript solution like jQuery Validation Plugin to validate data before sending to the server. Otherwise, send the data to the server, and return a the errors with a bad request if validation fails.
Eg.
Return BadRequest(string[]{"Name is required", "Id must me a number"});
then capture the errors and shoe to the user

HTML Forms post redirect

I've got an HTML form that I'm posting to a url successfully. However, I need to have the page be redirected after I've posted the form. I'm not able to use ajax because CORS is not enabled. When I post to the url I'm getting a success message, and a redirect link in json format. This seems much easier than it's proving to be.
What I know is, when I post to the original url, a cookie is created, and when I go to the url that the page is returning, I am an authenticated user. So, it seems that I need to capture that cookie, and then redirect, but I could be off base.
This can be achieved using custom scripting.
The script waits for the input button to be clicked and sets up a listener that checks to see if the div that holds the confirmation text is visible and then sends the user to the destination page.
Add this to the code injection point for the page that holds the form:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var eventposted=0;
$(document).ready(function(){
$('input.button').click(function() {
window.setInterval(foo, 100);
});
});
function foo(){
if(($(".form-submission-text").is(':visible')) && (eventposted==0)){
window.location = "http://www.something.com/destinationpage";
eventposted=1;
}
}
</script>

Websecurity logout link using Webmatrix and Razor

I am creating an application largely based on the template provided with WebMatrix 2.
Everything is working great, although I'm having some issues creating a "logout" link in my header.
Currently I have the following link:
Sign Out
Which in turn, directs to this page:
#{
WebSecurity.RequireAuthenticatedUser();
if (IsPost) {
// Verify the request was submitted by the user
AntiForgery.Validate();
// Log out of the current user context
WebSecurity.Logout();
// Redirect back to the return URL or homepage
var returnUrl = Request.QueryString["ReturnUrl"];
Context.RedirectLocal(returnUrl);
} else {
Response.Redirect("~/");
}
}
But when I click this link, it does nothing, and I'm still logged in. Where am I going wrong?
The problem is that by default logout links are (and should be) validated POST requests, this is to prevent XSS attacks of logging your users out by redirecting them to the logout page.
Thanks to this code:
if (IsPost) {
// Verify the request was submitted by the user
AntiForgery.Validate();
.. you will need to create a form for logging out, like so:
<form method="post" action="~/account/logout.cshtml">
#AntiForgery.GetHtml()
<input type="submit" value="Logout" />
</form>
Of course, you can use JavaScript to have a normal link submit that form, thus making it look like a normal link to the end user, only they're protected!