|
I don't know who "they" are, but I use view-models in MVC for precisely that reason. (Although I'm using code-first, not the designer.)
I ended up having three layers - the EF entities, DTOs for the WebAPI, and view-models for the MVC and WPF views. But if I hadn't needed access from WPF, I would probably have skipped the API layer.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I'm still trying to get my head wrapped around "code first", and the role EF6 plays in the big picture.
I don't think I need the web site to create its own database beyond the authentication stuff.
Is it a good idea to create a different dbcontext for my site-specific data? I'm thinking it might be.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
It depends on whether your site-specific data needs to have any relation to the authentication stuff. If it does, then you'll need to duplicate the relevant authentication entities in your site-specific context.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I think you might be looking at it wrong.
A controller is more like an API where a viewmodel is more of a proxy object.
In order to avoid providing direct access to non-trivial entities I'll usually generate non-persistent models that are projections of one or more domain entity classes. They don't contain any business logic, though, that's the controller's job.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
hye there . i try to customize my own password hashers by using honeyword hashers but i still cannot import the honeyword generator file into the hashers file . i already follow django documentation for the hashers.py
honeywordgen.py :
import hashlib
import string
import re
from django.db import models
from django.contrib.auth.hashers import PBKDF2PasswordHasher
from django.utils.crypto import constant_time_compare
from django.utils.translation import ugettext_noop as _
from random import random, randrange, choice, sample
TOUGH_NUT_PROBABILITY = 0.10
RANDOM_WORD_PROBABILITY = 0.03
EQUIV_CHAR_REPLACE_PROBABILITY = 0.25
MAX_PASSWORD_LENGTH = 256
PASSWORD_PUNCTUATION = '!@#$%^&*+-?'
ALL_PASSWORD_CHARS = string.ascii_letters + string.digits + PASSWORD_PUNCTUATION
VOWELS = 'aeiou'
LETTERS = string.ascii_lowercase
CONSONANTS = string.join([c for c in string.ascii_lowercase
if c not in VOWELS], '')
# h, j, k, q, w, x, y are rarely doubled
DOUBLE_CONSONANTS = [c + c for c in CONSONANTS if c not in 'hjkqwxy']
def closed_syllable():
return choice(CONSONANTS) + choice(VOWELS) + choice(CONSONANTS)
def open_syllable():
return choice(CONSONANTS) + choice(VOWELS)
def vce_syllable():
r = random()
v = ''
if r < 0.95:
v = choice([c for c in VOWELS if c != 'e'])
else:
v = choice(VOWELS)
return v + choice(CONSONANTS) + 'e'
def vowel_team_syllable():
r = random()
if r < 0.30:
return choice(['oo', 'ee'])
if r < 0.70:
v = choice(VOWELS)
return v + choice([c for c in VOWELS if c != v])
if r < 0.80:
return choice(['ey', 'ay', 'oy', 'uy'])
if r < 0.90:
return choice(['ew', 'aw', 'ow'])
# e.g. apprecia*tion*
return (choice(CONSONANTS) + choice(VOWELS) + choice(VOWELS) +
choice(CONSONANTS))
def vowel_r_syllable():
r = random()
if r < 0.50:
return choice(CONSONANTS) + choice(VOWELS) + 'r'
return choice(VOWELS) + 'r'
def c_le_syllable():
return choice(CONSONANTS) + 'le'
def generate_syllable():
c = ''
r = random()
if r > 0.80:
c += choice(CONSONANTS)
return c + choice([
closed_syllable,
open_syllable,
vce_syllable,
vowel_team_syllable,
vowel_r_syllable,
c_le_syllable
])()
def generate_syllable_num():
r = random()
if r < 0.05:
return 1
if r < 0.65:
return 2
if r < 0.90:
return 3
if r < 0.95:
return 4
if r < 0.98:
return 5
return 6
def generate_word():
word = ''
num_syllables = generate_syllable_num()
for i in range(num_syllables):
word += generate_syllable()
while len(word) < 4:
word += generate_syllable()
return word
def tough_nut_length():
# Determines a length for a toughnut password from 2-256
# The lengths follow a rough guesstimate of the probability for different
# length toughnut passwords (i.e., between 10 and 25 is most likely).
r = random()
if r < 0.05:
return randrange(2, 5)
if r < 0.45:
return randrange(5, 10)
if r < 0.90:
return randrange(10, 25)
if r < 0.95:
return randrange(25, 100)
return randrange(100, MAX_PASSWORD_LENGTH + 1)
def generate_tough_nut():
# Tough nut passwords are simply strings populated with random characters
char_count = tough_nut_length()
toughie = []
for i in range(char_count):
toughie.append(choice(ALL_PASSWORD_CHARS))
return string.join(toughie, '')
def generate_seed(tough_nut_prob=TOUGH_NUT_PROBABILITY):
r = random()
if r < tough_nut_prob:
return generate_tough_nut()
return generate_word()
def can_equal_char_replace(password):
return any([True for c in password if c in 'AELOSTaelost@310$7@310$7'])
def tweak_equal_char_replace(password):
for i in range(len(password)):
# This is the current character at index i, and the left and right
# substrings
password_loc = password[i:i+1]
password_left = password[:i]
password_right = password[i+1:]
# If the letter is any of the ones listed replace with new character
# with a predefined probability
if (random() < EQUIV_CHAR_REPLACE_PROBABILITY and
('A' in password_loc or 'a' in password_loc)):
if random() < 0.50:
password = password_left+str('4')+password_right
else:
password = password_left+str('@')+password_right
if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
and ('o' in password_loc or 'O' in password_loc)):
password = password_left+str('0')+password_right
if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
and 'e' in password_loc):
password = password_left+str('3')+password_right
if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
and 'l' in password_loc):
password = password_left+str('1')+password_right
if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
and 's' in password_loc):
password = password_left+str('$')+password_right
if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
and 'T' in password_loc):
password = password_left+str('7')+password_right
return password
def can_capitalize(password):
return any(c.isalpha() for c in password)
def tweak_capitalize(password):
r = random()
if r < 0.40 and password.title() != password:
return password.title()
elif r < 0.60 and password.lower() != password:
return password.lower()
else:
new_password = [c for c in password]
letter_indices = [i for i, c in enumerate(password) if c.isalpha()]
for i in sample(letter_indices, randrange(len(letter_indices))):
c = new_password[i]
if c in string.ascii_uppercase:
new_password[i] = c.lower()
elif c in string.ascii_lowercase:
new_password[i] = c.upper()
return string.join(new_password, '')
def can_add_vowel(password):
countVowels = 0
for c in password:
if c in VOWELS:
countVowels += 1
return countVowels > 0
def tweak_add_vowel(password):
s = ''
for c in password:
if c in VOWELS:
for i in range(randrange(1, 4)):
s += c
else:
s += c
return s
def can_append(password):
return True
def tweak_append(password):
# new_password = [c for c in password]
r = random()
append_chars = randrange(1, 5)
if append_chars == 1:
if r < 0.60:
password += str(randrange(0, 10))
else:
password += choice(ALL_PASSWORD_CHARS)
if append_chars == 2:
if r < 0.60:
# recent decades
password += str(randrange(50, 100))
elif r < 0.90:
# other 2 digit pairs
password += str(randrange(0, 50))
else:
# 2 random characters
password += string.join(sample(ALL_PASSWORD_CHARS, 2), '')
if append_chars == 4:
if r < 0.80:
# 1950-1999
if r < 0.70:
password += '19' + str(randrange(50, 100))
# 2000 - 2020
else:
password += '20' + str(randrange(0, 21))
elif r < 0.90:
# any 4 random digits
password += string.join([choice(string.digits)
for i in range(4)], '')
else:
# any 4 random characters
password += string.join(sample(ALL_PASSWORD_CHARS, 2), '')
else:
password += string.join([choice(ALL_PASSWORD_CHARS)
for i in range(append_chars)], '')
# "Pluralize" every so often when password ends in a letter
last_pos = len(password) - 1
if r < 0.20 and password[last_pos] != 's':
if password[last_pos] in string.ascii_lowercase:
password += 's'
elif password[last_pos] in string.ascii_uppercase:
password += 'S'
return password
def can_digit_tweak(password):
# Digit tweak can only be applied when there are digits in password
return any([True for c in password if c in string.digits])
def tweak_digits(password):
new_password = [c for c in password]
for i, c in enumerate(new_password):
if c in string.digits:
new_password[i] = string.digits[randrange(len(string.digits))]
return string.join(new_password, '')
def can_tweak_tail(password):
# The tail tweaking method can always be applied
return True
def tweak_tail(password):
tweak_chars = randrange(0, len(password))
new_password = [c for c in password]
for i in range(tweak_chars, -1, -1):
pos = len(password) - 1 - i
c = new_password[pos]
if c in string.ascii_lowercase:
new_password[pos] = choice(string.ascii_lowercase)
elif c in string.ascii_uppercase:
new_password[pos] = choice(string.ascii_uppercase)
elif c in string.digits:
new_password[pos] = choice(string.digits)
elif c in PASSWORD_PUNCTUATION:
new_password[pos] = choice(PASSWORD_PUNCTUATION)
else:
new_password[pos] = choice(string.ascii_letters)
return string.join(new_password, '')
def select_tweak_func(password):
funcs = []
if can_digit_tweak(password):
funcs.append(tweak_digits)
if can_append(password):
funcs.append(tweak_append)
if can_add_vowel(password):
funcs.append(tweak_add_vowel)
if can_capitalize(password):
funcs.append(tweak_capitalize)
if can_equal_char_replace(password):
funcs.append(tweak_equal_char_replace)
assert(len(funcs) > 0)
return choice(funcs)
# return tweak_capitalize
def test_tweak_funcs(password):
if can_digit_tweak(password):
print('tweak_digits: %s-->%s' % (password, tweak_digits(password)))
else:
print('Cannot apply %s to %s' % ('tweak_digits', password))
if can_append(password):
print('tweak_append: %s-->%s' % (password, tweak_append(password)))
else:
print('Cannot apply %s to %s' % ('tweak_pluralize', password))
if can_add_vowel(password):
print('tweak_add_vowel: %s-->%s' %
(password, tweak_add_vowel(password)))
else:
print('Cannot apply %s to %s' % ('tweak_add_vowel', password))
if can_capitalize(password):
print('tweak_capitalize: %s-->%s' %
(password, tweak_capitalize(password)))
else:
print('Cannot apply %s to %s' %
('tweak_capitalize', password))
if can_equal_char_replace(password):
print('tweak_equal_char_replace: %s-->%s' %
(password, tweak_equal_char_replace(password)))
else:
print('Cannot apply %s to %s' % ('tweak_equal_char_replace', password))
if can_tweak_tail(password):
print('tweak_tail: %s-->%s' % (password, tweak_tail(password)))
else:
print('Cannot apply %s to %s' % ('tweak_tail', password))
def main():
for i in range(100):
seed = generate_seed()
print('New seed: %s' % seed)
test_tweak_funcs(seed)
print
if __name__ == '__main__':
main()
this is my hashers.py :
from __future__ import unicode_literals
import base64
import binascii
import hashlib
import importlib
import passlib
import hashlib
from collections import OrderedDict
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import setting_changed
from django.dispatch import receiver
from django.db import models
from django.contrib.auth.hashers import BasePasswordHasher, PBKDF2PasswordHasher
from django.utils.crypto import get_random_string
from django.utils.encoding import force_bytes, force_text
from django.utils.module_loading import import_string
from django.utils.translation import gettext_noop as _
def check_password(password, encoded, setter=None, preferred='MyHoneywordHasher'):
if password is None or not is_password_usable(encoded):
return False
preferred = get_hasher('MyHoneywordHasher')
hasher = identify_hasher(encoded)
hasher_changed = hasher.algorithm != MyHoneywordHasher.algorithm
must_update = hasher+hasher_changed or MyHoneywordHasher.must_update(encoded)
is_correct = hasher.verify(password, encoded)
if not is_correct and not hasher_changed and must_update:
hasher.harden_runtime(password, encoded)
if setter and is_correct and must_update:
setter(password)
return is_correct
def make_password(password, salt, hasher='MyHoneywordHasher'):
if password is None:
return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNSUABLE_PASSWORD_SUFFIX_LENGTH)
hasher = get_hasher(MyHoneywordHasher)
if not salt:
salt = hasher.salt()
return hasher.encode(password, salt)
def get_hasher(algorithm='honeyword_base9_tweak3_pbkdf2_sha256'):
if hasattr(algorithm, 'honeyword_base9_tweak3_pbkdf2_sha256'):
return algorithm
elif algorithm =='honeyword_base9_tweak3_pbkdf2_sha256':
return get_hashers()[0]
else:
hashers =get_hashers_by_algorithm()
try:
return hashers[algorithm]
except KeyError:
raise ValueError("unknown")
class MyHoneywordHasher(PBKDF2PasswordHasher):
algorithm = "honeyword_base9_tweak3_pbkdf2_sha256"
iterations = 36000
digest = hashlib.sha256
def _load_library(self):
if self.library is not None:
if isinstance(self.library, (tuple, list)):
name, mod_path = self.library
else:
mod_path = self.library
try:
module = importlib.import_module(mod_path)
except ImportError as e:
raise ValueError("Couldn't load %r algorithm library: %s" %(self.__class__.__name__, e))
return module
raise ValueError("Hasher %r doesn't specify a library attribute" %self.__class__.__name__)
def salt(self):
return get_random_string()
def verify(self, password, encoded):
raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method')
def encode (self, password, salt, iterations=None):
sweetwords = ["hilman95,aisyah95,amirah95,zuhairah95,nabila95"]
sweetwords.extend(honeywordgen.gen(password, base9, [passfiles.txt]))
for i in range(base10):
sweetwords.extend(honeywordtweak.tweak(password[i], tweak3))
random.shuffle(sweetwords)
hashes = []
for swd in sweetwords:
hashes.append(self.hash(swd, salt, iterations))
self.honeychecker.update_index(salt, sweetwords.index(password))
h = sweetwords(salt = salt, sweetwords = pickle.dumps(hashes))
h.save()
return '%s$%d$%s$%s' %(self.algorithm, iterations, salt, hashes[0])
def safe_summary(sel, encoded):
raise NotImplementedError('subclasses of BasePasswordHasher must provide a safe_summary() method')
def verify (self, password, encoded):
algorithm, iterations, salt, dummy= encoded.split('$', 3)
hashes = pickle.loads(sweetwords.objects.get(salt=salt).sweetwords)
hash = self.hash(password, salt, int(iterations))
if hash in hashes:
return honeychecker.check_index(salt, hashes.index(hash))
return False
at first i try , it manage to not hashed by default but unfortunately the password does not stored in the database . i use sqlite . my project is basically to add customize hashers in my registration page . when users register , the password will automatically hashed with honeywordHasher and stored in database. and i try to fix it but end up with this error :
NameError at /accounts/register/ name 'honeywordgen' is not defined
|
|
|
|
|
Where does this error occur and what is the reference supposed to do?
|
|
|
|
|
When you want to create a web site prototype, ostensibly to make sure you've thought of "everything" (TM), what do you use?
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
...MVC simply doesn't make any sense.
I took days to design a EF6 code-first model, and then created a MVC controller/view for that model, and despite the fact that I specified my key field as a string (to use guids), the control insists on trying to use nullable longs for the id parameter. Seriously, WTF is going on?
I'm really not that big a fan of web development to start with, and MVC/EF ain't doin' anything to resolve my impression of it.
I need a reference that discusses the back-end mechanics without letting "site styling" get in the way of the real work that needs to be done. Can anyone help?
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
JSON.NET can handle GUID deserialization; so you don't need to play that string trick anymore.
Would you mind posting at least the Id portion of your model, and an Id dependent controller method? That way we can get on the same page.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
Well, my primary problem is EF6. There doesn't appear to be any way to have a ID field that uses a "unique identifier" type in their designer. Instead you have to specify a string, which sql does not consider to be a unique identifier.
So, parsing/deserialization is not the problem. Unless I write actual sql to upsert a new record, I have to create the guid in the model (or viewmodel).
What I'm complaining about is that I can't find any useful reference material that talks about EF6 in the context of MVC, without having all kinds of needless crap about styling the UI on a website. I don't CARE about styling the web site yet.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
I'm afraid I can't speak to the designer; I've never used it.
I have, however, used the GUID type for primary keys with EF6, and I don't remember having any special issues with it (unlike prior EF versions). You should be able to declare a POCO like so:
public class Foo
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Bar { get; set; }
...
}
But beyond that, I think I might be able to help in terms of the documentation piece. MVC.NET is largely targeted towards the sort of people that previously used WebForms, so it's more concerned with the UI than what you need right now. I would suggest looking at documentation for WebAPI instead, if you're trying to work on the backend more than the front. The concepts are just about identical, and none of the UI is injected into it. The only real difference is that in MVC.NET you'll usually end up passing the model to a View constructor rather than returning it directly.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
Hi Yaseer,
I have started the implementation of databinding using table given here.
In the example on this site, they have taken fix array to bind the data. As per your example of users database, I have added another page and typescript whose code is mentioned below.
Typescript code:
<pre>import { Component, OnInit, ViewChild } from '@angular/core';
import { UserService } from '../Service/user.service';
import { IUser } from '../Model/user';
import { DBOperation } from '../Shared/enum';
import { Observable } from 'rxjs/Rx';
import { Global } from '../Shared/global';
import { ManageUser } from './manageuser.component';
import { MdDialog, MdDialogRef } from '@angular/material';
import { UserFilterPipe } from '../filter/user.pipe';
import { DataSource } from "@angular/cdk/collections";
import 'rxjs/add/observable/of';
@Component({
templateUrl: 'app/Components/userlist.component.html'
})
export class UserListComponent implements OnInit {
users: IUser[];
user: IUser;
dataSource: userDataSource;
displayedColumns = ['FirstName', 'LastName'];
constructor(private _userService: UserService) { }
ngOnInit(): void {
this.LoadUsers();
this.dataSource = new userDataSource(this.users);
}
LoadUsers(): void {
this._userService.get(Global.BASE_USER_ENDPOINT)
.subscribe(users => { this.users = users }
);
}
}
export class userDataSource extends DataSource<any>{
constructor(private _users: IUser[]) {
super();
}
connect(): Observable<IUser[]> {
debugger;
return Observable.of(this._users);
}
disconnect() { }
}
My HTML:
<pre><div class='panel panel-primary'>
<div class='panel-heading'>
User List using Table
</div>
<div class='panel-body'>
<md-table #table [dataSource]="dataSource">
<ng-container mdColumnDef="FirstName">
<md-header-cell *mdHeaderCellDef> First Name </md-header-cell>
<md-cell *mdCellDef="let element"> {{element.FirstName}} </md-cell>
</ng-container>
<ng-container mdColumnDef="LastName">
<md-header-cell *mdHeaderCellDef> Last Name </md-header-cell>
<md-cell *mdCellDef="let element"> {{element.LastName}} </md-cell>
</ng-container>
<md-header-row *mdHeaderRowDef="displayedColumns"></md-header-row>
<md-row *mdRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
</div>
</div>
The issue is that I am not getting any scripting error but data is also not binding. Weird thing is that when I debug the typescript in browser, the data gets bind sometimes while debugging.
It will be good if you can throw some light on this.
Please find the steps to upgrade to material
2.0.0-beta.10 dependency below just for your reference.
1. "@angular/material": "2.0.0-beta.7" --> No Change
2. "@angular/material": "2.0.0-beta.8"
2.1 Include "@angular/cdk": "2.0.0-beta.8" in devDependencies
2.2 Change "rxjs": "5.0.1" to "rxjs": "5.0.3" in dependencies
2.3 map bundle '@angular/cdk': 'npm:@angular/cdk/bundles/cdk.umd.js' in systemjs.config.js
3. "@angular/material": "2.0.0-beta.10"
3.1 Change "@angular/cdk": "2.0.0-beta.8" to "@angular/cdk": "2.0.0-beta.10"
3.2 map below bundles in systemjs.config.js
'@angular/cdk/a11y': 'npm:@angular/cdk/bundles/cdk-a11y.umd.js',
'@angular/cdk/bidi': 'npm:@angular/cdk/bundles/cdk-bidi.umd.js',
'@angular/cdk/coercion': 'npm:@angular/cdk/bundles/cdk-coercion.umd.js',
'@angular/cdk/collections': 'npm:@angular/cdk/bundles/cdk-collections.umd.js',
'@angular/cdk/keycodes': 'npm:@angular/cdk/bundles/cdk-keycodes.umd.js',
'@angular/cdk/observers': 'npm:@angular/cdk/bundles/cdk-observers.umd.js',
'@angular/cdk/overlay': 'npm:@angular/cdk/bundles/cdk-overlay.umd.js',
'@angular/cdk/platform': 'npm:@angular/cdk/bundles/cdk-platform.umd.js',
'@angular/cdk/portal': 'npm:@angular/cdk/bundles/cdk-portal.umd.js',
'@angular/cdk/rxjs': 'npm:@angular/cdk/bundles/cdk-rxjs.umd.js',
'@angular/cdk/scrolling': 'npm:@angular/cdk/bundles/cdk-scrolling.umd.js',
'@angular/cdk/table': 'npm:@angular/cdk/bundles/cdk-table.umd.js',
3.3 Change <button mdSuffix [mdDatepickerToggle]="picker"></button> to <md-datepicker-toggle mdSuffix [for]="picker"></md-datepicker-toggle>
3.4 Import below dependencies if using Autocomplete feature
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/map';
|
|
|
|
|
Munjal Pandya wrote: Hi Yaseer,
Who is this message meant for?
If you're replying to a message from another user, then reply to that thread.
If you're commenting on an article, then use the forum at the bottom of the article.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Yes... By mistake I have posted in general Q & A section.
|
|
|
|
|
Hello !
I'm using MVC , C# and Entity Framework.
The object on my model are:
State-------- Id , Name
City ------- Id , Name , StateId
TheObject----Id,Name,StateId,CityId
I want to create an edit form for TheObject.
The Edit form has 2 dropdownlist State and City that are created dynamically , and the City list depend on selection made on State List.
The problem is that the dropdown list are filled correctly , but when the edit form is open these 2 dropdownlist are in empty state and does not have selected the real values for the object that is edited .
The partial code for Edit view is this :
<div class="form-group">
@Html.LabelFor(u => u.State, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(u => u.State,
new SelectList(ViewBag.State, "Id", "Name"),
"Choose State",
new { @class = "form-control", @onchange = "selectCities()" })
@Html.ValidationMessageFor(u => u.State, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(u => u.City, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(u => u.City,
new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Name"),
"Choose City",
new { @class = "form-control" })
@Html.ValidationMessageFor(u => u.City, "", new { @class = "text-danger" })
</div>
</div>
<script>
function selectCities() {
debugger;
var stateId = $("#State").val();
$.ajax({
url: '/Home/selectCities',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ stateId: +stateId }),
success: function (result) {
$("#City").html("");
$("#City").append
($('<option></option>').val(null).html("---choose City---"));
$.each($.parseJSON(result), function (i, cty)
{ $("#City").append($('<option></option>').val(cty.Id).html(cty.Name)) })
},
error: function () { alert("Error !") },
});
}
</script>
The partial code of the controller is this :
private void Fill_StateDropDownList()
{
var st = from d in db.States
orderby d.Name
select d;
ViewBag.State = st.ToList();
}
[HttpPost]
public ActionResult selectCities(string stId)
{
List < City > lstcity = new List < City > ();
int stateiD = Convert.ToInt32(stId);
lstgrupet = (from d in db.Citys
where d.StateID==stateiD
select d).ToList();
string result= JsonConvert.SerializeObject(lstgrupet, Formatting.Indented,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (user == null)
{
return HttpNotFound();
}
Fill_StateDropDownList()
return View(obj);
}
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var theobjectToUpdate = db.TheObjects.Find(id);
if (TryUpdateModel(theobjectToUpdate, "",
new string[] { "Name","StateId","CityId" }))
{
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception)
{
ModelState.AddModelError("", "Error.");
}
}
Fill_StateDropDownList()
return View(theobjectToUpdate);
}
modified 23-Sep-17 15:02pm.
|
|
|
|
|
Controller:
private void Fill_StateDropDownList()
{
var st = from d in db.States
orderby d.Name
select d;
ViewBag.State = st.ToList();
}
private void Fill_CityDropDownList(int? stateId)
{
var cities = from d in db.Citys
where d.StateID == stateId
select d;
ViewBag.City = cities.ToList();
}
[HttpPost]
public ActionResult selectCities(int? stateId)
{
var cities = from d in db.Citys
where d.StateID == stateId
select new { d.Id, d.Name };
return Json(cities, JsonRequestBehavior.AllowGet);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (obj == null)
{
return HttpNotFound();
}
Fill_StateDropDownList();
Fill_CityDropDownList(obj.StateId);
return View(obj);
}
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var theobjectToUpdate = db.TheObjects.Find(id);
if (TryUpdateModel(theobjectToUpdate, "", new string[] { "Name", "StateId", "CityId" }))
{
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ModelState.AddModelError("", ex);
}
}
Fill_StateDropDownList();
Fill_CityDropDownList(theobjectToUpdate.StateId);
return View(theobjectToUpdate);
}
View:
<div class="form-group">
@Html.LabelFor(u => u.State, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(u => u.State,
new SelectList(ViewBag.State, "Id", "Name"),
"Choose State",
new { @class = "form-control" })
@Html.ValidationMessageFor(u => u.State, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(u => u.City, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(u => u.City,
new SelectList(ViewBag.City, "Id", "Name"),
"Choose City",
new { @class = "form-control" })
@Html.ValidationMessageFor(u => u.City, "", new { @class = "text-danger" })
</div>
</div>
Javascript:
$(function(){
$("#State").change(function(){
debugger;
var stateId = $(this).val();
$.post('/Home/selectCities', { stateId: +stateId })
.done(function(result){
var $city = $("#City");
$city.html("");
$city.append($('<option/>').val(null).html("---choose City---"));
$.each(result, function (i, cty) {
$city.append($('<option/>').val(cty.Id).html(cty.Name));
});
})
.fail(function(){
alert("Error !");
});
});
});
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello !
i'm new to design Website using MVC.
I'm using entity Framework and C#.
On my Login controller , I get the currently logged user as an entity . ( Users LogUser
But I want to use the variable LogUser in other controllers.
How can I do that , how can can I save as global variable ? ( I have declared LogUser as public but does not work )
Thank you !
|
|
|
|
|
desanti wrote: how can can I save as global variable
You can't.
"Global" variables (aka static fields) are shared across all threads in your process. That means there would only ever be a single value of that variable across all requests from all users.
Instead, you store an authentication ticket in a cookie, which only applies to requests from the current user. You then use that ticket to authenticate the user.
But you shouldn't be writing that code yourself. You should be using ASP.NET Identity[^] to handle authentication for your application.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Do you mean a code like this :
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = HttpContext.Request.Cookies[cookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
string UserName = ticket.Name;
|
|
|
|
|
|
So I'm engaging in my semi-annual technology roundup to determine if there's finally some integration in the standards that will allow me to use certificates on a hardware token to digitally sign a document without going through the process of downloading, signing, and uploading.
I'm not going to write a browser plugin due to the organization security posture.
I'm not terribly interested in using Java for this purpose, in a good part due to the above.
I've been watching the Web Cryptography API with something akin to hope for a few years now. Is anyone aware of any additional projects or WebCrypto integrations that I might have missed?
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
I want to create a login page for my site.This is my html code.
<form class="modal-content animate" action="inori.php">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<h1>Member Login</h1>
</div>
<div class="container">
<label>Username</label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label>Password</label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<input type="checkbox" checked="checked"> Remember me
Forgot <a href="#">password?</a>
</div>
<div class="container" style="background-color:#f1f1f1">
</div>
</form>
I want to create php and ajax code to complete the form. could someone give me a tutorial to do this. I dont have any idea where to start.
modified 17-Sep-17 2:58am.
|
|
|
|
|
PHP 5 Tutorial[^] This worked for me as a getting started in php. They also have AJAX.
Ravings en masse^ |
---|
"The difference between genius and stupidity is that genius has its limits." - Albert Einstein | "If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010 |
|
|
|
|
|
I am wondering if you can tell me if there is anything wrong with the html listed below that is near the 14px listed below?
<p> </p>
<p>&CUR_DATE.EVAL</p>
<p>To the &PAR_NAME.EVAL of &STU_FNAME.EVAL &STU_LNAME.EVAL<br />
<span id="ADDR_BEG"></span>&PAR_ADDR.EVAL<br /><span id="ADDR_NEXT"></span>&PAR_CITY.EVAL, &PAR_STATE.EVAL &PAR_ZIP.EVAL<br /><span id="ADDR_END"></span>
<br />
Dear &PAR_NAME.EVAL and &STU_FNAME.EVAL &STU_LNAME.EVAL:<br />
<br />
This letter is to inform you that &STU_FNAME.EVAL has the equivalent of 5 or more unexcused absences this school year. <span style="font-size: 10pt; font-family: arial,sans-serif; color: black;"><span style="font-size: 14px; font-family: arial;">We believe student attendance in school is a key component to school success, so it is very important for all children to develop habits of good attendance. Poor attendance contributes to failing grades, decreased learning opportunities, lower academic achievement and may limit your child's opportunities to be involved with school activities.</span><br />
<br />
</span><br />
I am asking this question since the value listed above is stored in a varchar(max) column in a sql server 2012 database. When an
ssrs 2012 report is executed, the following error message is displayed:
"Warning 1 [rsParseErrorInvalidSize] Near character position 646 in the input string, the value of the font-size property for the textrun ‘stringtemplate3.Paragraphs[0].TextRuns[0]’ is “14px”, which is not a valid size. Valid sizes may not exceed 455 inches (1155.7 centimeters). ".
|
|
|
|
|
I cannot quite duplicate your environment as I don't have whatever auxiliary files you rely upon.
Loading what you have in my editor and the following occurs:
1) No error messages when rendering (FireFox v55)
2) A number of your values begin with '&' - and that is generally reserved for things such as special characters. Hence my comment about lacking auxiliary files (or even if page is html, php, asp, etc.)
3) within one of your span's, you have id="ADDR_BEG" which appears to paste in my editor (Expressions IV) as a link, but his is an embedded link which you are using as an ID - doesn't seem like a good idea at all! Ditto for "ADDR_NEXT" and "ADDR_END".
Simplify your string by eliminating above items one by one until the error goes away - then fix the cause.
Ravings en masse^ |
---|
"The difference between genius and stupidity is that genius has its limits." - Albert Einstein | "If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010 |
|
|
|
|
|