SignUp is not registering the user - salesforce-lightning

I am building a custom registration page for the community users to sign up in the experience cloud.
Unfortunately my code is not creating any user when i click on Sign Up.
Could someone help me please.
Below are the codes:
Lightning Component:
<aura:component controller="LightningSelfRegisterController" implements="forceCommunity:availableForAllPageTypes" access="global" >
<aura:attribute name="accountId" type="String" required="false" description="accountId for creating the user. If not specified, it will create a PersonAccount if possible for B2C scenario. Or otherwise if it's in a community, the community's self-registration accountId will be used."/>
<aura:attribute name="regConfirmUrl" type="String" required="true"/>
<aura:attribute name="startUrl" type="String" required="false" description="The url you go to after a successful login" />
<aura:attribute name="showError" type="Boolean" required="true" description="" default="false" access="private"/>
<aura:attribute name="errorMessage" type="String" required="false" description="" access="private"/>
<aura:attribute name="firstnameLabel" type="String" required="false" default="First Name"/>
<aura:attribute name="lastnameLabel" type="String" required="true" default="Last Name"/>
<aura:attribute name="emailLabel" type="String" required="false" default="Email"/>
<aura:attribute name="CompanyNameLabel" type="String" required="false" default="Company Name"/>
<aura:attribute name="CityLabel" type="String" required="false" default="City"/>
<aura:attribute name="CountryLabel" type="String[]" required="false"/>
<aura:attribute name="TitleLabel" type="String" required="false" default="Title"/>
<aura:attribute name="passwordLabel" type="String" required="false" default="Create Password"/>
<aura:attribute name="confirmPasswordLabel" type="String" required="false" default="Confirm Password"/>
<aura:attribute name="submitButtonLabel" type="String" required="false" default="Sign Up"/>
<aura:attribute name="includePasswordField" type="Boolean" required="false" default="false" description="Whether to include password"/>
<aura:attribute name="explicitOptIn" type="Boolean" required="false" default="false"/>
<aura:attribute name="EmailOptIn" type="Boolean" required="false" default="false"/>
<aura:attribute name="extraFieldsFieldSet" type="String" required="false" description="A field set name whose fields are desired for user registration"/>
<aura:attribute name="extraFields" type="list" required="false" description="A field set name whose fields are desired for user registration"/>
<aura:attribute name="targetVal" type="string"/>
<aura:attribute name="expid" type="String" required="false" description="The branding experience ID" />
<aura:handler name="init" value="{!this}" action="{!c.initialize}"/>
<aura:handler event="c:setExpId" action="{!c.setExpId}"/>
<aura:dependency resource="c:setExpId" type="EVENT"/>
<div>
<aura:renderIf isTrue="{!v.showError}">
<div id="error">
<ui:outputRichText value="{!v.errorMessage}"/>
</div>
</aura:renderIf>
<div id="sfdc_username_container" class="sfdc">
<span id="sfdc_user" class="login-icon" data-icon="a"></span>
<ui:inputText value="" aura:id="firstname" placeholder="{!v.firstnameLabel}" keyup="{!c.onKeyUp}" class="input sfdc_usernameinput sfdc"/>
</div>
<div id="sfdc_nickname_container" class="sfdc">
<span id="sfdc_user" class="login-icon" data-icon="a"></span>
<ui:inputText value="" aura:id="lastname" placeholder="{!v.lastnameLabel}" keyup="{!c.onKeyUp}" required = "true" class="input sfdc_usernameinput sfdc"/>
</div>
<div id="sfdc_email_container" class="sfdc">
<span id="sfdc_user" class="login-icon" data-icon="k"></span>
<ui:inputText value="" aura:id="email" placeholder="{!v.emailLabel}" keyup="{!c.onKeyUp}" class="input sfdc_usernameinput sfdc"/>
</div>
<div id="sfdc_nickname_container" class="sfdc">
<span id="sfdc_user" class="login-icon" data-icon="a"></span>
<ui:inputText value="" aura:id="CompanyName" placeholder="{!v.CompanyNameLabel}" keyup="{!c.onKeyUp}" class="input companynameinput sfdc"/>
</div>
<div id="sfdc_nickname_container" class="sfdc">
<span id="sfdc_user" class="login-icon" data-icon="a"></span>
<ui:inputText value="" aura:id="City" placeholder="{!v.CityLabel}" keyup="{!c.onKeyUp}" class="input cityinput sfdc"/>
</div>
<div id="sfdc_nickname_container" class="sfdc">
<span id="sfdc_user" class="login-icon" data-icon="a"></span>
<ui:inputSelect class="sfdc" aura:id="country" label = "Country" change="{!c.changeTarget}" value="{!v.targetVal}">
<ui:inputSelectOption text="Select"/>
<aura:iteration items="{!v.CountryLabel}" var="statusVar">
<ui:inputSelectOption value="{!statusVar.value}"/>
</aura:iteration>
</ui:inputSelect>
</div>
<div id="sfdc_nickname_container" class="sfdc">
<span id="sfdc_user" class="login-icon" data-icon="a"></span>
<ui:inputText value="" aura:id="Title" placeholder="{!v.TitleLabel}" keyup="{!c.onKeyUp}" class="input Titlenameinput sfdc"/>
</div>
<aura:renderIf isTrue="{!v.includePasswordField}">
<div id="sfdc_password_container" class="sfdc">
<ui:inputSecret value="" aura:id="password" placeholder="{!v.passwordLabel}" keyup="{!c.onKeyUp}" class="input sfdc_passwordinput sfdc"/>
</div>
<div id="sfdc_confirm_password_container" class="sfdc">
<ui:inputSecret value="" aura:id="confirmPassword" placeholder="{!v.confirmPasswordLabel}" keyup="{!c.onKeyUp}" class="input sfdc_passwordinput sfdc"/>
</div>
</aura:renderIf>
<div id="sfdc_opt_in_container" class="sfdc">
<ui:inputcheckbox aura:id="checkbox1" change="{!c.explicitOpt}" class="input sfdc_explicitOptIn sfdc"/>
<a>Accepting our Policy</a>
</div>
<div class="sfdc">
<ui:button aura:id="submitButton" label="{!v.submitButtonLabel}" press="{!c.handleSelfRegister}" class="sfdc_button"/>
</div>
</div>
</aura:component>
Lightning Controller
({
initialize: function(component, event, helper) {
$A.get("e.siteforce:registerQueryEventMap").setParams({"qsToEvent" : helper.qsToEventMap}).fire();
$A.get("e.siteforce:registerQueryEventMap").setParams({"qsToEvent" : helper.qsToEventMap2}).fire();
helper.CountryLabelHelper(component,event,helper);
},
handleSelfRegister: function (component, event, helper) {
helper.handleSelfRegister(component, event, helpler);
},
onKeyUp: function(component, event, helper){
//checks for "enter" key
if (event.getParam('keyCode')===13) {
helpler.handleSelfRegister(component, event, helpler);
}
},
changeTarget:function(component, event, helper){
var targetVal = component.find('targetId').get('v.value');
//alert('targetVal ' + targetVal);
component.set('v.targetVal}',targetVal);
}
})
Lightning Controller Helper
({
qsToEventMap: {
'startURL' : 'e.c:setStartUrl'
},
qsToEventMap2: {
'expid' : 'e.c:setExpId'
},
handleSelfRegister: function (component, event, helper) {
var firstname = component.find("firstname").get("v.value");
var lastname = component.find("lastname").get("v.value");
var lastnameval = component.find("lastname");
var email = component.find("email").get("v.value");
var companyname = component.find("CompanyName").get("v.value");
var city = component.find("City").get("v.value");
var action = component.get("c.selfRegister");
var explicitoptin = component.find("Explicit Opt-In").get("v.explicitoptin");
var password = component.find("password").get("v.value");
var confirmPassword = component.find("confirmPassword").get("v.value");
action.setParams({firstname:firstname,lastname:lastname,email:email,
companyname:companyname, city:city, explicitoptin:explicitoptin, password:password, confirmPassword:confirmPassword});
action.setCallback(this, function(a){
var rtnValue = a.getReturnValue();
if (rtnValue !== null) {
component.set("v.errorMessage",rtnValue);
component.set("v.showError",true);
alert('Record saved successfully');
}
});
$A.enqueueAction(action);
},
setBrandingCookie: function (component, event, helpler) {
var expId = component.get("v.expid");
if (expId) {
var action = component.get("c.setExperienceId");
action.setParams({expId:expId});
action.setCallback(this, function(a){ });
$A.enqueueAction(action);
}
},
setExpId: function (component, event, helper) {
var expId = event.getParam('expid');
if (expId) {
component.set("v.expid", expId);
}
helper.setBrandingCookie(component, event, helper);
},
explicitOpt: function(component,event) {
var checkbox = component.find('checkbox1').get('v.checked');
component.set("v.Contact.Explicit_Opt_In__c",checkbox);
},
CountryLabelHelper: function(component, event, helper) {
var action = component.get("c.pickList");
action.setParams({"obj":"Contact", "str":"Country__c"});
action.setCallback(this, function(response){
var state = response.getState();
if(state == "SUCCESS"){
var result = response.getReturnValue();
component.set("v.CountryLabel",result);
}
});
$A.enqueueAction(action);
}
})
Lightning Controller Apex Class:
global class LightningSelfRegisterController{
public LightningSelfRegisterController() {
}
#TestVisible
private static boolean isValidPassword(String password, String confirmPassword) {
return password == confirmPassword;
}
#TestVisible
private static boolean siteAsContainerEnabled(String communityUrl) {
Auth.AuthConfiguration authConfig = new Auth.AuthConfiguration(communityUrl,'');
return authConfig.isCommunityUsingSiteAsContainer();
}
#TestVisible
private static void validatePassword(User u, String password, String confirmPassword) {
if(!Test.isRunningTest()) {
Site.validatePassword(u, password, confirmPassword);
}
return;
}
#AuraEnabled
public static String selfRegister(String firstname ,String lastname, String email, String password, String confirmPassword, String accountId, String regConfirmUrl, String extraFields, String startUrl, Boolean includePassword,String CompanyName,String city,Boolean explicitoptin) {
Savepoint sp = null;
try {
sp = Database.setSavepoint();
if (lastname == null || String.isEmpty(lastname)) {
return Label.Site.lastname_is_required;
}
if (email == null || String.isEmpty(email)) {
return Label.Site.email_is_required;
}
User u = new User();
u.Username = email;
u.put('Email',email);
u.FirstName = firstname;
u.LastName = lastname;
u.CompanyName = companyName;
u.City = city;
String networkId = Network.getNetworkId();
// If using site to host the community the user should not hit s1 after logging in from mobile.
if(networkId != null && siteAsContainerEnabled(Network.getLoginUrl(networkId))) {
u.put('UserPreferencesHideS1BrowserUI',true);
}
String nickname = ((firstname != null && firstname.length() > 0) ? firstname.substring(0,1) : '' ) + lastname.substring(0,1);
nickname += String.valueOf(Crypto.getRandomInteger()).substring(1,7);
u.put('CommunityNickname', nickname);
if (includePassword) {
if (!isValidPassword(password, confirmPassword)) {
return Label.site.passwords_dont_match;
}
validatePassword(u, password, confirmPassword);
}
else {
password = null;
}
// lastName is a required field on user, but if it isn't specified, we'll default it to the username
String userId = Site.createPortalUser(u, accountId, password);
// create a fake userId for test.
if (Test.isRunningTest()) {
userId = 'fakeUserId';
}
if (userId != null) {
if (password != null && password.length() > 1) {
ApexPages.PageReference lgn = Site.login(email, password, startUrl);
if(!Test.isRunningTest()) {
aura.redirect(lgn);
}
}
else {
ApexPages.PageReference confirmRef = new PageReference(regConfirmUrl);
if(!Test.isRunningTest()) {
aura.redirect(confirmRef);
}
}
}
return null;
}
catch (Exception ex) {
Database.rollback(sp);
return ex.getMessage();
}
}
#AuraEnabled
global static String setExperienceId(String expId) {
// Return null if there is no error, else it will return the error message
try {
if (expId != null) {
Site.setExperienceId(expId);
}
return null;
} catch (Exception ex) {
return ex.getMessage();
}
}
#AuraEnabled
public static List<String> pickList(String obj, String str) {
List<String> regList = new List<String>();
Schema.DescribeFieldResult plistvalues = Schema.getGlobalDescribe().get(obj).getDescribe().fields.getMap().get(str).getDescribe();
for(PicklistEntry ent:plistvalues.getpicklistvalues()) {
regList.add(ent.getLabel());
}
return regList;
}
}
Could someone please let me know what Should i need to correct here.

Related

Vue3: How to get error messages with Bootstrap and VeeValidate 4?

I want to use vue3 together with bootstrap 4/5 with veevalidate 4.
<template>
<Form as="form" #submit.prevent="onFormSubmit" class="needs-validation" :class="{ 'was-validated': wasValidated }">
<div class="form-group">
<label for="firstNameId">First Name *</label>
<Field name="firstname" as="input" id="firstNameId" type="text" rules="required|firstname" class="form-control" placeholder="First Name" v-model="firstName" aria-describedby="input-true input-false input-help" aria-invalid="true" />
<ErrorMessage as="div" name="firstname" v-slot="{ message }">
{{ message }}
<div class="invalid-feedback">
{{ message }}
</div>
</ErrorMessage>
<div class="valid-feedback">Good!</div>
</div>
<Form>
</template>
<script>
import { Field, Form, ErrorMessage, defineRule } from 'vee-validate';
defineRule('required', value => {
if (!value || !value.length) {
return 'This field is required.';
}
return true;
});
defineRule("firstname", (value) => {
if (!/^[a-zA-Z0-9( ),'.:/-]+$/i.test(value)) {
return "Please use only letters, numbers and the following special characters: ( ),'.:/-";
}
return true;
});
export default {
components: {
Form,
Field,
ErrorMessage
},
data () {
return {
firstName: "",
wasValidated: false,
},
methods: {
onFormSubmit(values) {
alert(JSON.stringify(values, null, 2));
console.log("Submitted");
console.log(values);
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
this.wasValidated = true;
}, false);
});
},
},
};
</script>
The problem is that I can't activate the div with the class invalid-feedback or valid-feedback.
I could add the class was-validated to the <form>-tag, but I get feedback first after the second click on the submit button.
<template>
<Form as="form"
#submit="onFormSubmit"
class="needs-validation"
:validation-schema="schema"
v-slot="{ errors }"
>
<div class="form-group">
<label for="firstNameId">First Name *</label>
<Field
name="firstName"
type="text"
placeholder="First Name"
v-model="firstName"
aria-describedby="input-true input-false input-help"
aria-invalid="true"
v-slot="{ meta, field }"
>
<input
v-bind="field"
name="firstName"
type="text"
class="form-control"
:class="{
'is-valid': meta.valid && meta.touched,
'is-invalid': !meta.valid && meta.touched,
}"
/>
</Field>
<ErrorMessage as="div" name="firstname" v-slot="{ message }" class="invalid-feedback">
{{ message }}
</ErrorMessage>
<Form>
</template>
<script setup>
import { markRaw } from 'vue';
import { Field, Form, ErrorMessage} from 'vee-validate';
import * as yup from 'yup';
</script>
<script>
export default {
components: {
Form,
Field,
ErrorMessage
},
data () {
return {
schema: markRaw(yup.object().shape({
firstName: yup.string().min(0).max(20).label('First Name'),
})),
};
},
methods: {
onFormSubmit(values) {
console.log(JSON.stringify(values, null, 2));
},
},
};
</script>

How to show/hide an element in real time (Blazor)?

I have an image I would like to display only after a user has filled in all text fields.
I have tried using disabled attribute, but that does not seem to work. Any other insights?
Here is my current code:
<EditForm EditContext="#EditContext" style="max-width:800px;" onkeydown="javascript: DisableEnterKey();">
<FluentValidator />
<img src="images/approval-16-grey.ico" alt="Image" disabled="#OkayDisabled">
<p class="statp">How many families and/or individuals are living on your land?</p><br />
<label class="statlabel" for="amountOfFamilies">Amount of families:</label><br />
<InputNumber id="fams" for="indivNum" class="input" #bind-Value="#familyData.IndividualAmount" onwheel="this.blur()" placeholder="Families..." autofocus />
<ValidationMessage For="() => familyData.IndividualAmount" />
<br /><hr class="statHR" />
<label class="statlabel" for="amountOfIndividuals">Amount of single individuals: </label><br />
<InputNumber id="individuals" for="famNum" class="input" #bind-Value="#familyData.FamilyAmount" onwheel="this.blur()" placeholder="Individuals..."/>
<ValidationMessage For="() => familyData.FamilyAmount" />
<br /><hr class="statHR" />
<label class="statlabel" for="names"> Please enter all of the names here:</label><br />
<InputTextArea id="names" class="textArea" rows="4" cols="18" #bind-Value="#PersonName" placeholder="Names of all individuals..." />
<ValidationMessage For="() => familyData.PersonName" />
</EditForm>
</div>
</ul>
#code
{
private EditContext? EditContext;
public FamilyData Model = new FamilyData();
protected string OkayDisabled { get; set; } = "disabled";
protected override void OnInitialized()
{
EditContext = new EditContext(Model);
EditContext.OnFieldChanged += EditContext_OnFieldChanged;
base.OnInitialized();
}
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
SetOkDisabledStatus();
}
private void EditContext_OnFieldChanged(object? sender, FieldChangedEventArgs e)
{
SetOkDisabledStatus();
}
private void SetOkDisabledStatus()
{
if(EditContext.Validate())
{
OkayDisabled = null;
}
else
{
OkayDisabled = "disabled";
}
}
}
The hidden html attribute also works to hide an element.
<p hidden>This paragraph should be hidden.</p>
To bind to Model:
<p hidden="#HideLabel">I am Hidden When HideLabel == true</p>
<p hidden="#(!HideLabel)">I am Hidden when Hidelabel == false</p>
<button #onclick="#Toggle">Show/Hide</button>
#code {
private bool HideLabel {get;set;} = false;
private void Toggle()
{
HideLabel = !HideLabel;
}
}
Edit: You can also use a CSS class to hide/show an element:
<div class="font-italic #(HideLabel ? "d-none" : "d-show")">
I am Hidden When HideLabel == true
</div>
Change OkayDisabled to a bool, and then around your image do this
#if (!OkayDisabled)
{
<img src=".....whatever" etc />
}
You might also want to add #bind:event="oninput" wherever you use an #bind.
Instead of binding your flag to the disabled attribute (an image's disabled attribute just grays it out), I would bind it to a css class that has display: none;
.hidden {
display: none;
}
<img class="#(ShouldShowImage? "hidden" : string.Empty)">
didn't used it within editform but should work
#if(OkayDisabled)
{
<img src="images/approval-16-grey.ico" >

Submit form to action with parameters, Asp.Net.Core Mvc

I am trying to submit sorting dropdown form via ajax in asp.net.core. Action has other parameters which I want to get in action too but form does not submit other parameters.
I think, the main problem is form part in razor
this is part my action :
public IActionResult Products( int? page, int? categoryId, string searchName = "", string
sortOrder="")
{
int pageSize = 1;
int pageNumber = (page ?? 1);
ViewBag.SearchName = searchName;
ViewBag.CategoryId = categoryId;
ViewBag.SortOrder = sortOrder;
........
model.ProductInfo = productList.ToList().ToPagedList(pageNumber,
pageSize);
if (isAjax)
return
PartialView("/Views/Shared/FrontPartialViews/_FrontProductList.cshtml",
model.ProductInfo);
else
return View("/Views/User/Products.cshtml", model);
}
here is form :
<form asp-controller="User" asp-action="Products"
asp-route- categoryId="#ViewBag.CategoryId"
asp-route-searchName="#ViewBag.searchName"
data-ajax="true"
data-ajax-method="Get"
data-ajax-update="product"
data_ajax_mode="replace">
<select name="sortOrder" class="form-control" onchange="orderByChanged()">
<option selected> Please select one</option>
<option value="date_desc">
date_desc
</option
<select>
</form>
Here is a working demo like below:
View(Index.cshtml):
<form asp-controller="User" asp-action="Products"
asp-route-categoryId="#ViewBag.CategoryId"
asp-route-searchName="#ViewBag.SearchName"
data-ajax="true"
data-ajax-method="Get"
data-ajax-update="product"
data_ajax_mode="replace">
<select name="sortOrder" class="form-control" onchange="orderByChanged()">
<option selected> Please select one</option>
<option value="date_desc">
date_desc
</option>
</select>
<input type="submit" value="Submit" class="btn btn-primary" />
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js" integrity="sha256-v2nySZafnswY87um3ymbg7p9f766IQspC5oqaqZVX2c=" crossorigin="anonymous"></script>
<script>
function orderByChanged() {
$('form').submit();
}
</script>
}
Controller:
Be sure set ViewBag.CategoryId and ViewBag.SearchName when you first render your view.
public IActionResult Products(int? page, int? categoryId, string searchName = "", string sortOrder = "")
{
int pageSize = 1;
int pageNumber = (page ?? 1);
ViewBag.SearchName = searchName;
ViewBag.CategoryId = categoryId;
ViewBag.SortOrder = sortOrder;
//....
}
public async Task<IActionResult> Index()
{
ViewBag.CategoryId = 1;
ViewBag.SearchName = "aaa";
return View();
}
Result:
Provide the action url in data-ajax-url:
<form method="get"
data-ajax="true"
data-ajax-method="get"
data-ajax-update="product"
data-ajax-mode="replace"
data-ajax-url="#Url.Action("Products", "User")">
<input type="hidden" name="categoryId" value="ViewBag.CategoryId" />
<input type="hidden" name="searchName" value="ViewBag.SearchName" />
<select name="sortOrder" class="form-control" onchange="orderByChanged()">
<option selected> Please select one</option>
<option value="date_desc">date_desc</option>
<select>
</form>

React updating state in two input fields from form submission

I am trying to make a simple contact form using React. Eventually I will send the data collected from the state to a database, but for right now I am trying to just get it to console log the correct values.
Right now, the email field overrides the name field and when I console log both states, name shows up and email is undefined. Here is my React Component
import React, { Component, PropTypes } from 'react';
import ContactData from '../data/ContactData.js';
class FormContact extends Component {
constructor(props) {
super(props)
this.state = {
name: '',
email: '',
textArea: ''
}
}
handleChange(event) {
event.preventDefault();
this.setState({
name: event.target.value,
email: event.target.email
})
}
handleSubmit(event) {
event.preventDefault();
console.log(this.state.name + ' ' + this.state.email);
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<label> Name:
<input type="text" placeholder="Name" value={this.state.name} onChange={this.handleChange.bind(this)} />
</label><br />
<label> Email:
<input type="text" placeholder="Email" value={this.state.email} onChange={this.handleChange.bind(this)}/>
</label><br />
<input className="btn btn-primary" type="submit" value="Submit" />
</form>
)
}
}
FormContact.PropTypes = {
subName: PropTypes.string,
subEmail: PropTypes.string
}
FormContact.defaultProps = {
subName: 'Sam',
subEmail: ''
}
class Contact extends Component {
render() {
return (
<div>
<h1>CONTACT PAGE</h1>
<FormContact />
</div>
)
}
}
export default Contact;
If I understand what you want, you could do it as follows :
Add an empty object in your state for the form values
formValues: {}
Add the name attribute to your fields
<input name="name" .... />
<input name="email" .... />
then depending on that name update your state in handleChange function
let formValues = this.state.formValues;
let name = event.target.name; // Field name
let value = event.target.value; // Field value
formValues[name] = value;
this.setState({formValues})
And if the values go one level deeper, you could use
value={this.state.formValues["name"]} instead of value={this.state.name} - where name is the value of the name attribute of your input field
Thus, everything together should be as follows :
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {
formValues: {}
}
}
handleChange(event) {
event.preventDefault();
let formValues = this.state.formValues;
let name = event.target.name;
let value = event.target.value;
formValues[name] = value;
this.setState({formValues})
}
handleSubmit(event) {
event.preventDefault();
console.log(this.state.formValues);
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<label> Name:
<input type="text" name="name" placeholder="Name" value={this.state.formValues["name"]} onChange={this.handleChange.bind(this)} />
</label><br />
<label> Email:
<input type="text" name="email" placeholder="Email" value={this.state.formValues["email"]} onChange={this.handleChange.bind(this)}/>
</label><br />
<input className="btn btn-primary" type="submit" value="Submit" />
</form>
)
}
}
React.render(<Test />, document.getElementById('container'));
Here is fiddle.
Hope this helps.
The reference to event.target.email does not exist on the event element. The value of a text input from an inline-event handler would be event.target.value for both email and name. The quick solution is to create a separate handler for each input:
handleChangeName(event) {
event.preventDefault();
this.setState({ name: event.target.value }); //<-- both use the same reference
} // to get the contextual value
handleChangeEmail(event) { // from the inputs v
event.preventDefault(); // |
this.setState({ email: event.target.value }); //<--------------------
}

Multiple file upload using Request.Files["files"] MVC

This is my Code. I want to uplade 3 file into my database
first in View I write this :
<% using (Html.BeginForm(Actionname, Controller, FormMethod.Post, new {enctype="multipart/form-data"})){%> .....
....
and this is 3 file uplaoding:
<input type="file" name="files" id="FileUpload1" />
<input type="file" name="files" id="FileUpload2" />
<input type="file" name="files" id="FileUpload3" />
In controller I use this code:
IEnumerable<HttpPostedFileBase> files = Request.Files["files"] as IEnumerable<HttpPostedFileBase>;
foreach (var file in files)
{
byte[] binaryData = null;
HttpPostedFileBase uploadedFile = file;
if (uploadedFile != null && uploadedFile.ContentLength > 0){
binaryData = new byte[uploadedFile.ContentLength];
uploadedFile.InputStream.Read(binaryData, 0,uploadedFile.ContentLength);
}
}
but the files always return NULL :(
please help me, thank you.
Try this instead:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) {%>
<input type="file" name="files" id="FileUpload1" />
<input type="file" name="files" id="FileUpload2" />
<input type="file" name="files" id="FileUpload3" />
<input type="submit" value="Upload" />
<% } %>
and the corresponding controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
// TODO: do something with the uploaded file here
}
}
return RedirectToAction("Index");
}
}
It's a bit cleaner.
You should use:
IList<HttpPostedFileBase> files = Request.Files.GetMultiple("files")
instead.