How can I change userID in the form (vue.js) - javascript

I am developing a web page. there i am using v-modal with vuejs. I am making an object form new Form. it gets. in the html it inserts the id which is input by user but i want to replace that with the userID gotten from the currently logged in user. i tried getter and settter in the script but it does not change the form.id. it takes the input from user . the following is my code. sorry for the messy code.
<template>
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0">Applications Page</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><router-link to="/dashboard">Home</router-link></li>
<li class="breadcrumb-item active">About Page</li>
</ol>
</div>
</div>
</div>
</div>
<div class="content">
<div class="container-fluid">
<div class="row mt-4">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Application</h3>
<div class="card-tools">
<button class="btn btn-success" #click="newModal">Add New
<i class="fa-regular fa-calendar-plus fa-fw"></i>
</button>
</div>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>ID</th>
<th>User_ID</th>
<!-- <th>body</th> -->
<!-- <th>category_id</th> -->
<!-- <th>user_id</th> -->
<th>Job_ID</th>
<th>Status</th>
<!-- <th>image</th> -->
<th>Modify</th>
</tr>
</thead>
<tbody>
<tr v-for="application in applications.data" :key="application.id">
<td> {{ application.id }}</td>
<td>{{ application.user_id }}</td>
<td>{{ application.job_id }}</td>
<td> {{ application.status }}</td>
<td>
<a href="#" #click="editModal(application)">
<i class="fa fa-edit blue"></i>
</a> /
<a href="#" #click="deleteApplication(application.id)">
<i class="fa fa-trash red"></i>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" v-show="!editmode" id="myModalLabel">Add New Application</h1>
<h1 class="modal-title fs-5" v-show="editmode" id="myModalLabel">Udate Application</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form #submit.prevent="editmode ? updateApplication() : createApplication() ">
<div class="modal-body">
<div class="form-group">
<input v-model="form.user_id" type="text" name="user_id" placeholder="user_id"
class="form-control" :class="{ 'is-invalid': form.errors.has('user_id') }">
<has-error :form="form" field="user_id"></has-error>
</div>
<!-- <input :value="userID" > -->
<!-- <div class="form-group"></div> -->
<!-- <select v-model="form.user_id">
<option :value=userID.id></option>
</select>
</div> -->
<!-- <input v-model="form.user_id" type="text" name="user_id" placeholder="user_id"
class="form-control" :class="{ 'is-invalid': form.errors.has('user_id') }"> <has-error :form="form" field="user_id"></has-error> -->
<div class="form-group">
<textarea v-model="form.job_id" type="text" name="job_id" placeholder="job_id"
class="form-control" :class="{ 'is-invalid': form.errors.has('job_id') }"></textarea>
<has-error :form="form" field="job_id"></has-error>
</div>
<div class="form-group">
<input v-model="form.status" type="text" name="status" placeholder="status"
class="form-control" :class="{ 'is-invalid': form.errors.has('status') }">
<has-error :form="form" field="status"></has-error>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
<!-- <button type="submit" class="btn btn-primary" data-bs-dismiss="modal">Create</button> -->
<button v-show="editmode" type="submit" class="btn btn-success">Update</button>
<button v-show="!editmode" type="submit" class="btn btn-primary">Create</button>
</div>
</form>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
import Form from 'vform';
import Swal from 'sweetalert2/dist/sweetalert2.js';
import 'sweetalert2/src/sweetalert2.scss';
export default {
data: () => ({
editmode: false,
applications: {},
// catIDs: {},
userID: {},
form: new Form({
id: '',
user_id: '',
job_id: '',
status: '',
// get newUserID (){
// return this.user_id;
// },
// set newUserID(newUser_id){
// this.user_id = newUser_id[0];
// }
})
}),
methods: {
updateApplication(id) {
this.form.put('api/application/' + this.form.id)
.then(() => {
$('#myModal').modal('hide');
Swal.fire('Application updated!');
// this.$emit('afterCreate');
this.loadApplication();
})
.catch(() => {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
});
},
newModal() {
this.editmode = false;
this.form.reset();
$('#myModal').modal('show');
},
editModal(application) {
this.editmode = true;
this.form.reset();
$('#myModal').modal('show');
this.form.fill(application);
},
deleteApplication(id) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
this.form.delete('api/application/' + id).then(() => {
Swal.fire(
'Deleted!',
'Application has been deleted.',
'success'
);
this.loadApplication();
}).catch((result) => {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
});
}
})
},
loadApplication() {
axios.get("api/application").then(({ data }) => (this.applications = data));
},
loadUserID() {
axios.get('api/applicationGetID').then(({ data }) => (this.userID = data));
console.log(this.form.user_id);
// axios.get('api/applicationGetID').then(({ data }) => (this.userID2 = data.[id]));
},
// loadCatId() {
// axios.get('api/categoryId').then(({ data }) => (this.catIDs = data));
// },
createApplication() {
// this.form.newUserID = this.userID;
console.log(this.form.user_id)
this.form.post('api/application')
.then(() => {
$('#myModal').modal('hide');
Swal.fire('Application created!')
this.loadApplication();
})
.catch(() => {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
})
}
},
created() {
this.loadApplication();
this.loadUserID();
// this.loadCatId();
}
}
</script>

Related

Graphql Mutations aren't working with Supabase and Postgraphile

i have been wracking my brain for hours on end with no success. My Graphql Mutation for a form isn't working but my Graphql queries are working fine. Any idea why with the below code? I'm using supabase as my database, postgraphile for graphql, nuxtjs for the ui
<template>
<div>
<form method="POST" #submit.prevent="createAgreement()">
<nav class="navbar navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand">
<input type="reset" class="btn btn-warning" value="Reset"></a>
<a class="navbar-brand">
<input type="submit" class="btn btn-warning" value="Save Agreement"></a>
</div>
</nav>
<br>
<div class="row">
<div class="col-3">
<!-- Tab navs -->
<div id="v-tabs-tab" class="nav flex-column nav-tabs text-center" role="tablist" aria-orientation="vertical">
<a id="v-tabs-home-tab" class="nav-link active" data-mdb-toggle="tab" href="#v-tabs-home" role="tab"
aria-controls="v-tabs-home" aria-selected="true">Create A New Agreement</a>
</div>
<!-- Tab navs -->
</div>
<div class="col-9">
<div id="v-tabs-tabContent" class="tab-scope">
<div id="v-tabs-home" class="tab-pane fade show active" role="tabpanel" aria-labelledby="v-tabs-home-tab">
<div class="table table-responsive">
<table class="table">
<tbody>
<tr>
<td style="text-align: right;">Agreement Name</td>
<td>
<input v-model="name" type="text" required />
</td>
</tr>
<tr>
<td style="text-align: right;">Agreement Type</td>
<td>
<input v-model="type" type="text" name="Type" />
</td>
</tr>
</tbody>
</table>
</div>
<br><br>
<div id="accordionExample" class="accordion">
<div class="accordion-item">
<h2 id="headingOne" class="accordion-header">
<button class="accordion-button" type="button" data-mdb-toggle="collapse"
data-mdb-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Content
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne"
data-mdb-parent="#accordionExample">
<div class="accordion-body">
<div class="table table-responsive">
<table class="table">
<tbody>
<tr>
<td style="text-align: right;">Excerpt</td>
<td>
<textarea id="excerpt" v-model="excerpt" type="textarea" cols="50" rows="10"
value="Add a short Description"></textarea>
</td>
</tr>
<tr>
<td style="text-align: right;">Description</td>
<td>
<textarea id="excerpt" v-model="content" type="textarea" cols="50" rows="10"
value="Add a Description"></textarea>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="accordion-item">
<h2 id="headingThree" class="accordion-header">
<button class="accordion-button" type="button" data-mdb-toggle="collapse"
data-mdb-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Images and Videos
</button>
</h2>
<div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree"
data-mdb-parent="#accordionExample">
<div class="accordion-body">
<td>
<input v-model="image" type="image" name="headshot" value="Select an image to upload"
help="Select a png, jpg or gif to upload." validation="mime:image/jpeg,image/png,image/gif" />
</td>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</template>
<script>
import gql from "graphql-tag";
import allAgreementsList from "~/apollo/queries/sales/agreements";
const ADD_AGREEMENTS = gql`
mutation ($name:String!,$excerpt:String,$type:String,$content:String,$image:String){
createAgreement(objects: {name: $name, excerpt: $excerpt, type: $type, content: $content, image: $image}) {
affected_rows
returning {
name
excerpt
type
content
image
}
}
}`;
export default {
data() {
return {
type: [],
name: " ",
excerpt: " ",
content: " ",
image: " ",
}
},
head: {
title: 'Add New Agreement'
},
methods: {
async addAgreement() {
const name = this.name;
const content = this.content;
const excerpt = this.excerpt;
const type = this.type;
const image = this.image;
await this.$apollo.mutate({
mutation: ADD_AGREEMENTS,
variables: {
name,
excerpt,
type,
content,
image,
},
update: (cache, { data: { insertAgreements }}) => {
// Read data from cache for this query
try {
const insertedAgreement = insertAgreements.returning;
console.log(insertedAgreement)
cache.writeQuery({
query: allAgreementsList
})
}
catch (err) {
console.error(err)
}
}
}).then(() => {
this.$router.push({path: '../sales/agreements'})
}).catch(err => console.log(err));
this.name = ' ';
this.excerpt = ' ';
this.type = ' ';
this.content = ' ';
this.image = ' ';
},
}
}
</script>
Also to note I have complete permissions on my database
So i switched systems and ended up using Apollo-Server, Prisma (my ORM), and Typegraphql just in case anyone wants a working solution with this combination:
import "reflect-metadata";
import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server";
import * as path from "path";
import { PrismaClient } from "#prisma/client";
import { resolvers } from "../prisma/generated/type-graphql";
interface Context {
prisma: PrismaClient;
}
async function main() {
const schema = await buildSchema({
resolvers,
emitSchemaFile: path.resolve(__dirname, "./generated-schema.graphql"),
validate: false,
});
const prisma = new PrismaClient();
await prisma.$connect();
const server = new ApolloServer({
schema,
context: (): Context => ({ prisma }),
});
const { port } = await server.listen(8001);
console.log(`GraphQL is listening on ${port}!`);
}
main().catch(console.error);
It also turned out to be a cors issue.

What causes the failure of a custom filter in this Vue 3 application?

I am working on a Users CRUD application with Vue 3. I want to display the users in reverse order (the latest addition should be on top) and for this purpose, I use the custom filter bolow:
reverse(array) {
return array.slice().reverse();
}
Instead of the desired result, I get a Property "reverse" was accessed during render but is not defined on instance error.
const usersApp = {
data() {
return {
users: [{
id: 1,
first_name: "John",
last_name: "Doe",
email: "john.doe#gmail.com"
},
{
id: 2,
first_name: "Jane",
last_name: "Doe",
email: "jane.doe#gmail.com"
}
],
formData: {
first_name: "",
last_name: "",
email: ""
},
formErrors: [],
userAdded: false
};
},
methods: {
isNotEmpty() {
return (
this.formData.first_name &&
this.formData.last_name &&
this.formData.email
);
},
isEmail(email) {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
},
formValidation() {
this.formErrors = [];
if (!this.isNotEmpty()) {
this.formErrors.push("There are empty filelds");
}
if (this.isNotEmpty() && !this.isEmail(this.formData.email)) {
this.formErrors.push("The email is invalid");
}
},
resetAddFormData() {
this.formData.first_name = "";
this.formData.last_name = "";
this.formData.email = "";
this.userAdded = false;
},
addUser() {
// Validate form data
this.formValidation();
// Make New User
let newUser = {
first_name: this.formData.first_name,
last_name: this.formData.last_name,
email: this.formData.email
};
// Add new user
if (!this.formErrors.length) {
this.users.push(newUser);
this.userAdded = true;
window.setTimeout(this.resetAddFormData, 1000);
}
}
},
watch: {
users() {
this.users();
}
},
filters: {
reverse(array) {
return array.slice().reverse();
}
}
};
Vue.createApp(usersApp).mount("#app");
.logo {
width: 30px;
}
.nav-item {
width: 100%;
}
#media (min-width: 768px) {
.nav-item {
width: auto;
}
}
.user-row {
transition: all 1s ease;
opacity: 1;
height: auto;
}
.user-row-active {
opacity: 0;
height: 0;
}
.alert {
padding: 0.6rem 0.75rem;
text-align: center;
font-weight: 600;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand p-0" href="#">
<img src="https://www.pngrepo.com/png/303293/180/bootstrap-4-logo.png" alt="" class="logo">
</a>
<!-- Links -->
<div class="navbar-nav w-100">
<ul class="navbar-nav ml-auto" id="navbarSupportedContent">
<li class="nav-item">
<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#exampleModalCenter">
Add user
</button>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="card my-2">
<h5 class="card-header px-2">Users</h5>
<div class="card-body p-0">
<table class="table table-striped m-0">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody name="users-table" is="transition-group">
<tr v-for="user in users | reverse" :key="user.id" class="user-row">
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title h6" id="exampleModalLongTitle">New User</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" #click="resetAddFormData">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div v-if="this.formErrors.length">
<div v-for="error in formErrors" class="alert alert-danger">
{{error}}
</div>
</div>
<div v-if="userAdded" class="alert alert-success">User added successfully!</div>
<form #submit.prevent="addUser" novalidate>
<div class="form-group mb-2">
<input type="text" class="form-control input-sm" placeholder="First name" v-model="formData.first_name">
</div>
<div class="form-group mb-2">
<input type="text" class="form-control input-sm" placeholder="Last name" v-model="formData.last_name">
</div>
<div class="form-group mb-2">
<input type="email" class="form-control input-sm" placeholder="Email address" v-model="formData.email">
</div>
<div class=" mt-2">
<button type="submit" class="btn btn-sm btn-block btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Questions:
What am I doing wrong?
Is there a better alternative to using a filter for this purpose?
Well, as the docs say filters can be used for common text formatting, therefore you can't use it over the array element, so the alternative solution to get a reversed array is to use computed properties.
So you can create a computed property like this:
reversedUsers() {
return this.users.slice().reverse();
}
Then get the results as below:
const usersApp = {
data() {
return {
users: [{
id: 1,
first_name: "John",
last_name: "Doe",
email: "john.doe#gmail.com"
},
{
id: 2,
first_name: "Jane",
last_name: "Doe",
email: "jane.doe#gmail.com"
}
],
formData: {
first_name: "",
last_name: "",
email: ""
},
formErrors: [],
userAdded: false
};
},
methods: {
isNotEmpty() {
return (
this.formData.first_name &&
this.formData.last_name &&
this.formData.email
);
},
isEmail(email) {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
},
formValidation() {
this.formErrors = [];
if (!this.isNotEmpty()) {
this.formErrors.push("There are empty filelds");
}
if (this.isNotEmpty() && !this.isEmail(this.formData.email)) {
this.formErrors.push("The email is invalid");
}
},
resetAddFormData() {
this.formData.first_name = "";
this.formData.last_name = "";
this.formData.email = "";
this.userAdded = false;
},
addUser() {
// Validate form data
this.formValidation();
// Make New User
let newUser = {
first_name: this.formData.first_name,
last_name: this.formData.last_name,
email: this.formData.email
};
// Add new user
if (!this.formErrors.length) {
this.users.push(newUser);
this.userAdded = true;
window.setTimeout(this.resetAddFormData, 1000);
}
}
},
watch: {
users() {
this.users();
}
},
computed: {
reversedUsers() {
return this.users.slice().reverse();
}
}
};
Vue.createApp(usersApp).mount("#app");
.logo {
width: 30px;
}
.nav-item {
width: 100%;
}
#media (min-width: 768px) {
.nav-item {
width: auto;
}
}
.user-row {
transition: all 1s ease;
opacity: 1;
height: auto;
}
.user-row-active {
opacity: 0;
height: 0;
}
.alert {
padding: 0.6rem 0.75rem;
text-align: center;
font-weight: 600;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand p-0" href="#">
<img src="https://www.pngrepo.com/png/303293/180/bootstrap-4-logo.png" alt="" class="logo">
</a>
<!-- Links -->
<div class="navbar-nav w-100">
<ul class="navbar-nav ml-auto" id="navbarSupportedContent">
<li class="nav-item">
<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#exampleModalCenter">
Add user
</button>
</li>
</ul>
</div>
</nav>
<div class="container">
<div class="card my-2">
<h5 class="card-header px-2">Users</h5>
<div class="card-body p-0">
<table class="table table-striped m-0">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody name="users-table" is="transition-group">
<tr v-for="user in reversedUsers" :key="user.id" class="user-row">
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title h6" id="exampleModalLongTitle">New User</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" #click="resetAddFormData">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div v-if="this.formErrors.length">
<div v-for="error in formErrors" class="alert alert-danger">
{{error}}
</div>
</div>
<div v-if="userAdded" class="alert alert-success">User added successfully!</div>
<form #submit.prevent="addUser" novalidate>
<div class="form-group mb-2">
<input type="text" class="form-control input-sm" placeholder="First name" v-model="formData.first_name">
</div>
<div class="form-group mb-2">
<input type="text" class="form-control input-sm" placeholder="Last name" v-model="formData.last_name">
</div>
<div class="form-group mb-2">
<input type="email" class="form-control input-sm" placeholder="Email address" v-model="formData.email">
</div>
<div class=" mt-2">
<button type="submit" class="btn btn-sm btn-block btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>

MVC4 Razor Modal not showing value passed into custom Javascript function with the onclick event handler

The modal opens. The "Id" value is displayed in the readonly textbox with id = "Id". But the Description value does not display in the readonly textbox with the id = "Description". I stepped through the code and the correct value is present in the function on the master view. However, it is not displaying in the modal. Am I missing something? Why is the value not passing to the Description id in the partial?
Partial
#model AutoClickItOnline.Models.AdminViewModels.DeleteSubTypeViewModel
#{
Layout = null;
}
#using (Html.BeginForm("DeleteSubType", "Admin", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, null, new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-12">
<label for="Id" class="text-dark">Subscription Type ID</label>
#Html.TextBoxFor(m => m.SubTypeId, new { #class = "form-control", #readonly = true, id = "Id" })
<label for="Name" class="text-dark pt-2">Descripiton</label>
#Html.TextBoxFor(m => m.Description, new { #class = "form-control", #readonly = true, id = "Description" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-success">Delete Subscription Type</button>
</div>
</div>
}
Javascript:
#section Scripts{
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#user_table').DataTable({
"scrollY": "50vh",
"scrollX": true,
"autowidth": false
});
});
function DeleteSubType(id, Description) {
$('#Id').val(id);
$('#Description').val(Description);
$('#DeleteSubTypeModal').modal('show')
}
</script>
}
Main View:
#model AutoClickItOnline.Models.AdminViewModels.SubscriptionTypeTableViewModel
#{
ViewBag.Title = "SubTypes";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<section>
<div class="container">
<div class="row py-5">
<div class="col">
<div class="modal fade" id="newSubTypeModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">New Subscription Type Entry</h2>
</div>
<div class="modal-body">
#{
Html.RenderPartial("/Views/Admin/AddSubTypePartial.cshtml", new SubscriptionType());
}
</div>
</div>
</div>
</div>
<div class="modal fade" id="DeleteSubTypeModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Delete Subscription</h2>
</div>
<div class="modal-body">
#{
Html.RenderPartial("/Views/Admin/DeleteSubTypePartial.cshtml", new AutoClickItOnline.Models.AdminViewModels.DeleteSubTypeViewModel());
}
</div>
</div>
</div>
</div>
<div class="d-flex flex-row">
<h2 class="pr-2">Subscription Type Manager</h2>
<a class="btn btn-sm btn-primary ml-auto my-2 text-light text-center d-none d-md-block" href="#" data-toggle="modal" data-target="#newSubTypeModal"><i class="fa fa-plus text-light pr-1"></i>Add New Subscription Type</a>
<a class="btn btn-sm btn-primary ml-auto my-2 text-light text-center d-sm-none" style="max-height:50px;" href="#" data-toggle="modal" data-target="#newSubTypeModal">ADD NEW</a>
</div>
#if (Model.Message != null)
{
<div class="text-danger">
#Html.DisplayFor(modelItem => Model.Message, null, new { #class = "text-danger" })
</div>
}
<hr />
<table id="user_table" class="display small-table table-bordered border-dark" style="width:100%;">
<thead>
<tr>
<th style="font-size:11px; min-width:195px;">Id</th>
<th style="font-size:11px;">Description</th>
<th style="font-size:11px;">Length</th>
<th style="font-size:11px;">Cost</th>
<th style="font-size:11px;">Active</th>
<th style="font-size:11px; min-width:100px;">Date/Time Created</th>
<th style="font-size:11px; min-width:60px;">Created By</th>
<th style="font-size:11px; min-width:105px;">Date/Time Modified</th>
<th style="font-size:11px; min-width:65px;">Modified By</th>
<th style="font-size:11px;">Delete</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.SubscriptionTypes)
{
<tr>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.SubscriptionTypeId)</td>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.Description)</td>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.Length)</td>
<td style="font-size:11px">$#Html.DisplayFor(modelItem => item.Cost)</td>
#if (item.Active)
{
<td style="font-size:11px">Yes</td>
}
#if (!item.Active)
{
<td style="font-size:11px">No</td>
}
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.DateTimeCreated) UTC</td>
<td style="font-size:11px">#AdminHelpers.GetUsersName(item.CreatedBy)</td>
<td style="font-size:11px">#Html.DisplayFor(modelItem => item.DateTimeModified) UTC</td>
<td style="font-size:11px">#AdminHelpers.GetUsersName(item.ModifiedBy)</td>
<td>
<input type="button" class="btn btn-sm btn-danger" value="X" onclick="DeleteSubType('#item.SubscriptionTypeId', '#item.Description'); return false;" />
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</section>

how can I make an v-if depending on a boolean object property?

I have a array of objects(comments from posts kind like facebook comments or any other social network) and I iterate it with an v-for, then I have on each comment a dropdown button with "edit" and "delete" buttons, I would like that when I press the edit button the comment would change to an input so I can edit it, so I added a property click_to_edit initialize in false to each comment object, so when I click on edit it changes the condition that the v-for is related to. But it does not change it, I guess it is that as the property is inside an object it always return false and therefore the condition never changes, but I do not know how else do this. This is the html for the v-for:
<div
class="mb-2"
v-bind:class="'comment_'+post.id"
v-for="(comment, index) in comments"
:key="index"
v-if="comment.id_post === post.id"
>
<div class="row">
<div class="col-img-user-post text-center">
<img
class="rounded-circle img-icon-profile"
:src="routes.user_files+'/'+comment.code+'/'+comment.picture"
alt
/>
</div>
<div class="col">
<div class="row">
<div class="col">
<div class="card-comment">
<div class="row">
<div v-if="!comment.clicked_to_edit" class="col">
<p class="mt-2 mb-2">{{ comment.description }}</p>
<p class="mb-0 font-smaller grey-color">{{ comment.time_ago }}</p>
</div>
<div v-if="comment.clicked_to_edit" class="col">
<input v-model="comment.description" type="text" />
<p class="mb-0 font-smaller grey-color">{{ comment.time_ago }}</p>
</div>
<div class="col-1">
<div class="row dropdown">
<div class="col">
<a
class="font-smaller"
type="button"
:id="'dropdownMenuButtonComment_'+index"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
>
<i class="fas fa-lg fa-angle-down grey-color"></i>
</a>
<div
class="dropdown-menu dropdown-menu-right"
:aria-labelledby="'dropdownMenuButtonComment_'+index"
>
<button
class="dropdown-item"
v-if="comment.id_user===profile_info.id_user"
#click="editComment(comment.id, index)"
>
<i class="far fa-edit"></i>
Edit
</button>
<button
class="dropdown-item"
data-toggle="modal"
data-target="#modalDeleteComment"
v-if="comment.id_user===profile_info.id_user"
#click="actionComment(comment.id, 2, index)"
>
<i class="far fa-trash-alt red-color"></i>
<span class="red-color">Delete</span>
</button>
<button
class="dropdown-item"
v-if="comment.id_user!==profile_info.id_user"
#click="actionComment(comment.id, 3)"
>
<i class="far fa-flag"></i>
Report
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
The object comment stated in the data:
comment: {
id: "",
id_post: "",
description: "",
clicked_to_edit: false,
id_user: this.profile_info.id_user,
code: this.profile_info.code,
name: this.profile_info.name,
surname_1: this.profile_info.surname_1,
surname_2: this.profile_info.surname_2,
nick: this.profile_info.nick,
picture: this.profile_info.picture,
role: this.profile_info.id_role,
time_ago: "0 minutes"
},
and the edit function:
editComment(id, index) {
this.comments[index].clicked_to_edit = true;
console.log(this.comments[index]);
},
I purposefully ignored your model, to show a general case. If you need help applying it to your case, let me know.
Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
el: '#app',
data: () => ({
comments: [
{ id: 'one', description: "test 1" },
{ id: 'two', description: "test 2" },
{ id: 'three', description: "test 3" }
].map(i => ({ ...i,
isEditing: false
}))
}),
methods: {
async toggleEditing(comment, index) {
const isOpening = !comment.isEditing;
this.comments
.filter(c => c.isEditing)
.forEach(c => c.isEditing = false);
if (isOpening) {
comment.isEditing = true;
await this.$nextTick();
this.$refs.comments[index].querySelector('input').focus()
}
},
blur: ev => ev.target.blur()
}
})
.comment {
min-height: 21px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(comment, i) in comments" ref="comments" :key="comment.id">
<div v-if="!comment.isEditing"
v-text="comment.description"
class="comment"
#click="toggleEditing(comment, i)"></div>
<div v-else>
<input v-model="comment.description"
#blur="toggleEditing(comment)"
#keyup.enter="blur"
/>
</div>
</div>
</div>

How to solve Ajax.BeginForm calling twice using asp.net mvc

My Question:
I have a main page some fields when user click save button using Ajax.BeginForm i'm saving the details this is working successsfuly.
Inside main form there is one button(task) when user click that button partial window will open then they will fill some details. when partial window save button clicking automatically main page save action method is calling...first it save partial save details then immediately its saving main page details also then i'm getting two time saved successfully message.
when main page save button click only it should save main page fields. when partial page save button click it should save partial page fields only(partial page save i'm using jquery.
Main Page:
#using (Ajax.BeginForm("savePhase", "Search", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "ChmHeaderPage",OnSuccess= "OnSuccessMain" }, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.ChangeRequestList.FirstOrDefault().changeId);
#Html.HiddenFor(model => model.ChangeRequestList.FirstOrDefault().Phase);
<div class="col-md-offset-0 panel-body">
<div class="form-group">
#Html.LabelFor(model => model.Importance, htmlAttributes: new { #class = "col-md-3 control-label" })
<div class="col-md-3">
#Html.DropDownListFor(model => model.ImportanceVal, new SelectList(Model.Importance, "OptionId", "OptionName", Model.ImportanceVal), new { #class = "form-control", #Title = "Message Need to be Show" })
</div>
#Html.LabelFor(model => model.Urgency, htmlAttributes: new { #class = "col-md-2 control-label" })
<div class="col-md-3">
#Html.DropDownListFor(model => model.UrgencyVal, new SelectList(Model.Urgency, "OptionId", "OptionName", Model.UrgencyVal), new { #class = "form-control", #Title = "Message Need to be Show" })
</div>
</div>
<div class="col-md-12 ">
#Html.Label("Enter Task*")
<button type="button" id="Analysisbtn" class="btn btn-link " data-toggle="modal" data-target="#myModal">Select Task</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-open strech-modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Analysis</h4>
</div>
<div class="modal-body">
#Html.Partial("_TaskPage")
</div>
</div>
</div>
</div>
</div>
<!-- Form actions -->
<div class="row panel-body">
<div class="col-md-12 text-center">
<button type="submit" name="buttonValue" class="btn btn-danger" value="Close">Save & Close</button>
<button type="submit" name="buttonValue" class="btn btn-primary" value="Save">Save</button>
</div>
</div>
</div>
}
Partial Page:
#model www.ChangeManagementTool.ViewModels.SearchViewModel
<div class="panel-group" id="accordion" role="tablist" aria-
multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
<i class="more-less glyphicon glyphicon-plus"></i>
Task
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse first" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<div class="table-responsive center-block" data-tab-content="#item.Key" style="display:#displayText">
<table class="table table-responsive sena" id=#item.Key>
<tr>
<th>Department</th>
<th>Plant</th>
<th>Country</th>
<th>Responsibles</th>
<th>DueDate</th>
</tr>
<tbody>
#foreach (var analysisTask in item.Value)
{
<tr>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
<td>
--DisplayFor code
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="form-group">
<div class="col-md-12 text-center">
<button type="submit" id="btnSaveReal" class="btn btn-primary ">Save Task </button>
</div>
</div>
}
</div>
</div>
</div>
jquery Save Coding
<script type="text/javascript">
$('#btnSaveReal').click(function (e) {
var listex = [];
debugger;
$('#RealTask tbody tr').each(function (index, ele) {
var saveItem2 = {
ChangeId: $('#ChangeIdR').val(),
PlantId: $('#PlantIdR' + index).val(),
DepartmentId: $('#DepartmentIdR' + index).val(),
MstTaskId: $('#MstTaskIdR' + index).val(),
AffectedItemId: $('#AffectedItemIdR' + index).is(":checked")
}
listex.push(saveItem2);
})
//Save Coding
var url = applicationRoot + '/Search/SaveRealizationTaskdetails';
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({ 'objmodelRel': listex, actionR: 'AnalyzeRealize' }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (Data) {
if (Data.status) {
alert(Data.responseText);
} else {
alert(Data.responseText);
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
function toggleIcon(e) {
$(e.target)
.prev('.panel-heading')
.find(".more-less")
.toggleClass('glyphicon-plus glyphicon-minus');
}
$('.panel-group').on('hidden.bs.collapse', toggleIcon);
$('.panel-group').on('shown.bs.collapse', toggleIcon);
Controller Code:
public ActionResult savePhase(SearchViewModel objmodel, string buttonValue)
{
save code---------------
return RedirectToAction("FetchChgReqDetails");
}
public JsonResult SaveRealizationTaskdetails(List<ChangeRequestRealizationTask> objmodelRel, string actionR)
{
--save code
return new JsonResult { Data = new { status = true, responseText = "Successfuly saved!" }, JsonRequestBehavior= JsonRequestBehavior.AllowGet };
}
As per your questions i will suggest you to try below this if it helpful to you.
First change Partial view button type="button" instead of type="submit"
and on main form submit send all data including Partial view data using AJAX

Categories

Resources