I want to set TempData in View Component so that i can check it in Login Action when there is error in View Component.
Here is my .ts file code
window.onload = function () {
fetch('../Controller/ActionName',
{
headers: {
RequestVerificationToken: (<HTMLInputElement>document.getElementById("Token")).value
}
})
.then((response) => {
if (response.status != 200) {
redirectToHomePage();
}
response.text().then((data) => {
document.getElementById("Id")!.innerHTML = data;
});
});
// Redirect to home page
function redirectToHomePage() {
var url = window.location.origin;
window.location.href = url + '/Login/Login/';
}
};
Below is the ViewComponent code
public IViewComponentResult TestViewComponent()
{
try
{
// Do code here
}
Catch(Exception ex){
TempData["Error"] = "Err msg";
return View(viewName)
}
return View(viewName);
}
TempData is set correctly in ViewComponent, but when response get back from .ts file from redirectToHomePage() function to Login/Login TempData will be null.
So how to get TempData in Login action
Thank you in advance
Here is a definition of ViewComponent.TempData,And in the link you can see the TempData only have get method,So you cannot pass the TempData to Login/Login.
Related
I accessed API to upload image and return the image URL with Vue app. I want to set API response value to imgUrl1 in data section. I' sure getting correct response in console but imgUrl1 is still empty. Anybody idea ?? Thank you so much !
Vue
data () {return
{
imgUrl1:'',→empty
}
},
methods: {
uploadFile1: function () {
var img_file1 = this.$refs.img1.files[0]
var params = new FormData()
params.append('image', img_file1)
params.append('client_name', this.tableSelected)
axios.post("http://127.0.0.1:5000/", params
).then(function (response) {
console.log(response.data)→image url exists
this.imgUrl1 = response.data
}).catch(function (error) {
for(let key of Object.keys(error)) {
console.log(key);
console.log(error[key]);
}
});
}
console.log(response.data)
https://storage.googleapis.com/dashboard_chichat/img/クライアント名/xxxxxxxxnQSkX6Wudy.jpg
try using arrow functions in your then callback so the value of this is your Vue component.
methods: {
uploadFile() {
...
axios.post('', params)
.then((response) => {
this.imgUrl1 = response.data
})
}
}
the equivalent of it without arrow functions is:
methods: {
uploadFile() {
...
const _this = this;
axios.post('', params)
.then(function (response) {
_this.imgUrl1 = response.data
})
}
}
export default function handler(req, res {
const {
method,
query: { pid },
} = req;
if (method === 'GET') {
if (pid) {
res.statusCode = 200;
res.end(`Post: ${pid}`);
} else {
try {
const error = 'No post id specified';
throw new Error(error);
} catch (err) {
res.statusCode = 400;
res.end(`error: ${err}`);
}
}
} else {
const error = `unsupported method ${method}`;
try {
throw new Error(error);
} catch (err) {
res.statusCode = 400;
res.end(`error: ${err}`);
}
}
}
If the route /posts/ is called (without specifying pid), the above will return the 404 page's HTML but not the intended error "No post id specified"
The unsupported route if-branch works correctly instead.
How to obtain the above-explained behavior?
Like this:
const Page = ({ error, pid }) => {
if(error) return <p>{error}</p>
return <p>The following Page ID was passed {pid}</p>
}
export async function getServerSideProps(context) {
const { pid } = context.query;
if(!pid || typeof pid === 'undefined'){
return {
props { error: 'No pid passed' }
}
}
return {
props: { pid }
}
}
export default Page;
On the server side you can get the passed param from context.query the param needs to have the same name as the file in this case [pid].js
Then you simply check if the param is null or undefined. If so you return an error to message in the props to the component. Otherwise you return the PID or do a server side fetch and return the data to the component.
How to execute code after action finished in vue js? this is my login action
login: async ({commit},loginDTO)=>{
return commit('login',loginDTO);
}
My login mutations is this:
login:(state, loginDTO)=>{
axios.post(loginEndpoint.login, loginDTO)
.then(resp => {
if(resp.data.statusCode == 1) {
state.user.userId = resp.data.userId;
state.user.response = resp.data.responseText;
localStorage.setItem("token", "token")
state.isLogin = true;
router.push({name: 'Systems'});
}
else{
alert(66);
state.user.response = resp.data.responseText;
}
})
.catch(err => {
})
}
And I call it from component like this:
methods:{
...mapActions(['login']),
async login1(){
const loginDTO = {
Username : this.user.Username,
Password: this.user.Password
};
await this.$store.dispatch('login',loginDTO);
this.$toastr.s("Message", "");
}
}
Now I need toast message but after action is completed.
Updated.
Make use of async-await, and await for async action to complete and sync mutation to commit before you show the toast:
// action
login: async ({commit},loginDTO)=>{
try {
const { data } = await axios.post(loginEndpoint.login, loginDTO)
commit('login', data.userId, data.responseText, true);
} catch(error) {
commit('login', null, error.message, false);
}
}
// mutation
login: (state, userId, response, isLogin) {
state.user.userId = userId;
state.user.response = response;
state.isLogin = isLogin
}
methods:{
...mapActions(['login']),
async login1(){
const loginDTO = {
Username : this.user.Username,
Password: this.user.Password
};
await this.$store.dispatch('login',loginDTO);
this.$toastr.s("Message", "");
}
}
I think all you need to do is call the toast function after the action complete as usual, callback function after ajax returns 200, for example, I used
https://github.com/ankurk91/vue-toast-notification
then run it like so on the callback
this.$toast.open('You did it!');
(make sure the toast has been registered on your vue instance)
I have a PhantomJs script in which I create a new wepage, inject jQuery into it and scrape a list of URL from it. After that I call a function passing the list of URL and create a new webpage for each one and try to recover certain information from it
var pageGlobal = require('webpage');
function createPage(){
var page = pageGlobal.create();
page.onAlert = function(msg) {
console.log(msg);
};
return page;
}
var page=createPage();
page.open('http://www.example.com/', function(status){
if ( status === "success" ) {
page.injectJs('jquery-1.6.1.min.js');
var urlList=page.evaluate(
function(){
var urlList=[];
window.console.log = function(msg) { alert(msg) };
$("td.row1>a").each(function(index, link) {
var link=$(link).attr('href');
urlList.push(link);
});
return urlList;
});
processUrlList(urlList);
}
});
function processUrlList(urlList){
for(i=0;i<urlList.length;i++){
var currentPage=createPage();
currentPage.open("http://www.example.com"+urlList[i], function(status){
if ( status === "success" ) {
if(currentPage.injectJs('jquery-1.6.1.min.js')===false){
console.log("Error en la inyeccion");
}
currentPage.evaluate(function() {
window.console.log = function(msg) { alert(msg) };
console.log("Evaluating");
$("showAdText").each(function(index, link) {
//Capture information about the entity in this URL
})
});
}
});
}
}
The problem is in the processUrlList function the injection of jQuery always fail returning false. Would it be a problem to create two or more page objects instead of reusing only one? What could be happening here?
Button event in view:
var target = '#Url.Action("Login", "Home")';
$.post(target, { UserName: $('#txtEmail').val(), userType: $('#selection').val(),
Password: $('#txtPassword').val() });
and This is controller Action method.This controller is inside the area.
I am Calling this controller from another controller action method.
[HttpPost]
public ActionResult Login(string Username, string userType, string password)
{
HealthCareDataContext dc = null;
try
{
dc = new HealthCareDataContext();
var usr = (from obj in dc.tblAdmins
where obj.Username == Username.Trim()
&& obj.Status == true
select obj).ToList();
if (usr.Count > 0)
{
FormsAuthentication.Authenticate(Username, password); //Redirect login page.
FormsAuthentication.RedirectFromLoginPage(Username.Trim(), false);
return RedirectToAction("Index", "Admin", new { area1 = "Secure", area2 = "Admin" });
}
else
{
return View();
}
}
catch (Exception ex)
{
return View();
}
finally
{
dc = null;
}
}
This Action method is called but it does not return the view. But when i go through the URL manually it return the view.
Where i am doing wrong with calling this action.
$.post(target, { UserName: $('#txtEmail').val(), userType: $('#selection').val(),
Password: $('#txtPassword').val() }, function(result){
//Now check your result
});
I still have doubt that you have to do this because you are using redirectoaction inside login which will create problem.
If you want to return then try pure ajax call like this.
$.ajax({
type: 'POST',
url: target,
data: $.param({ UserName: $('#txtEmail').val(), userType: $('#selection').val(),
Password: $('#txtPassword').val() }) ,
success: function (result) {
alert(result);
},
error: function (result) {
alert('Error');
}
});