Meteor / React / Flow Router / Passing parameters to JSX - meteor

Simple question here: In Meteor with React how do I pass a parameter to .jsx . I want to send the :token param to my jsx so I can use it after the form submit.
I'm using kadira's flow-router and react-layout packages
Route
FlowRouter.route('/reset/:token',{
name: 'reset',
action: function(params){
ReactLayout.render(App, {
content: <Reset token={params.token} />
})
}
})
Reset.jsx
Reset = React.createClass({
resetPass(e){
e.preventDefault();
alert("test");
},
render() {
return (
<form onSubmit={this.resetPass}>
<input type="password" id="password"/>
<input type="password" id="confirmation"/><br /><br />
<input type="submit" id="reset-button" value="Reset password" />
</form>
);
}
})

Solved
I can get the info with this.props.token
Reset = React.createClass({
resetPass(e){
e.preventDefault();
alert(this.props.token);
},
render() {
return (
<form onSubmit={this.resetPass}>
<input type="password" id="password"/>
<input type="password" id="confirmation"/><br /><br />
<input type="submit" id="reset-button" value="Reset password" />
</form>
);
}
})

Related

I try to upload images and input text field to ASP Net Core Web API but controller not read (Angular 13, NET 5)

I need to upload product details and product images into ASP.NET core web API. I implement HTML files as below
<form [formGroup]="myForm" (ngSubmit)="submit()">
<mat-card>
<h2 class="fw-bold text-center">Product Management</h2>
<label class="fw-bold" for="">Product Name</label>
<input type="text" name="name" id="name" formControlName="ProductName" class="form-control">
<input type="text" name="description" id="description" placeholder="Product Description" class="form-control mt-3 mb-2" formControlName="ProductDescription">
<input type="text" name="price" id="price" placeholder="Product Price" class="form-control mt-3 mb-2" formControlName="price">
<input type="text" name="created" id="created" placeholder="Product created" class="form-control mt-3 mb-2" formControlName="created">
<input type="text" name="cat" id="cat" placeholder="Product created" class="form-control mt-3 mb-2" formControlName="ProductCatID">
<input type="file" name="Image" id="Image" class="form-control mt-3 mb-2" (change)="onFileChange($event)" formControlName="ImageUrl">
<img [src]="imageSrc" *ngIf="imageSrc" style="height: 300px; width:500px">
<button type="submit" class="btn btn-primary btn-block mt-3">Submit</button>
</mat-card>
</form>
This is TS file i have implement for the submit data
submit(){
console.log(this.myForm.value);
this.http.post('https://localhost:5001/api/Products', this.myForm.value)
.subscribe(res => {
console.log(res);
alert('Uploaded Successfully.');
})
}
I have implemented Controller As bellow. this controller not read
[HttpPost]
public async Task<ActionResult<ProductDto>> CreateProductAsync(CreateProductDto pro, IFormFile Image)
{
try
{
if (Image == null || Image.Length == 0)
{
return Content("File not selected");
}
var path = Path.Combine(_environment.WebRootPath, "wwwroot//images", Image.FileName);
//Saving the image in that folder
using (FileStream stream = new FileStream(path, FileMode.Create))
{
await Image.CopyToAsync(stream);
stream.Close();
}
pro.ImageUrl = Image.FileName;
var productEntity = _mapper.Map<Product>(pro);
var newProduct = _SqlService.AddProduct(productEntity);
var productForReturn = _mapper.Map<ProductDto>(newProduct);
return CreatedAtRoute("GetProduct", new { id = productForReturn.ProId },
productForReturn);
}
catch(Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
Folder Structure
I need to upload images into the web API folder and as well as I need store the image and product details in SQL Database

How should I reference an element created in React-Typescript and change its CSS properties?

I have a form which needs its css Display to be set to block when I click on a certain button. When I click on the Add button id="add" it should set the css style block for id="modalContent" div.
I've just started react and am completely new to it. I read something about ref but couldn't completely understand how to go through with it.
AddFormMod.tsx
import React from 'react';
import './App.css';
function AddForm(){
return (
<div id="modalContent" className="modal-content">
<h1 id="headerAdd">ADD NEW CONTACT</h1>
<form action="#" id="myForm">
<label className="required label" ><b>Name: </b></label><br />
<input className="form-fields type1" type="text" id="name" name="name" required></input><br/><br/>
<label className="required label" ><b>Email:</b> </label><br/>
<input className="form-fields type1 " type="email" id="email" name="mail" required></input><br/><br/>
<label className="required label" ><b>Mobile:</b> </label>
<label className="label" id="landlinelabel" ><b>Landline:</b></label><br/>
<input className="form-fields" type="tel" id="mobile" name="mobile" pattern="^\d{10}$" required></input>
<input className="form-fields" type="tel" id="landline" name="landline" ></input><br/><br/>
<label className="label" ><b>Website</b></label><br/>
<input className="form-fields type1" type="text" id="website" name="website" ></input><br/><br/>
<label className="label"><b>Address:</b> </label><br/>
<textarea className="addressstyle form-fields" id="address1" name="address1" rows={9} cols={74}></textarea>
<input className = "buttonstyle" type="submit" value="Add" id="adddetails" ></input>
<input className = "buttonstyle" type="button" value="Cancel" id="candetails"></input>
</form>
</div>
);
}
export default AddForm;
App.tsx
import React from 'react';
import './App.css';
import AddForm from './AddFormMod';
function App() {
return (
<p id="title"> Address Book </p>
);
}
function AddHome(){
return (
<div>
<button id="home" >HOME</button>
<button id="add" onClick={} >+ADD</button>
</div>
);
}
function ContactBar(){
return (
<div>
<p id="contacts">CONTACTS</p>
</div>
);
}
export { App , AddHome, ContactBar };
One approach to achieve the result you want, is to utilize conditional rendering. For example, when you click the "add"-button in your AddHome component, you can set a state variable to render the AddForm-component:
function AddHome(){
const [shouldRenderForm, setShouldRenderForm] = useState(false);
return (
<div>
<button id="home" >HOME</button>
<button id="add" onClick={() => setShouldRenderForm(true)} >+ADD</button>
{shouldRenderForm && <AddForm />}
</div>
);
}
I'm also guessing you want to "close the form" after submit or via a close button inside the AddForm-component. To achieve this, simply pass a prop to the component, for the AddForm-component to call to close the form:
// ... in the add AddHome component:
{shouldRenderForm && <AddForm closeForm={() => setShouldRenderForm(false)} />}
// ... in AddForm component:
type AddFormProps = { closeForm: () => void };
function AddForm({ closeForm }: AddFormProps) {
// ... i.e. on a button to close the form
<button type="button" onClick={() => closeForm()}>Cancel</button>
}
Checkout a working example in this sandbox.

Multiple Submit Buttons in Razor Pages not able to find handler pageName?handler=OnPostUploadImage

I am trying to upload Image using Ajax method in asp.net core Razor pages, I am main form in will all input fields are kept and with the form for Fileupload i am also added addition button which is for file upload using Ajax, When i hit the
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
i want it to call OnPostUploadImage method in pageModel file but it alway goes to default OnPost method. when i rename the OnPost to OnPost2 nothing happend..
How can i call OnPostUploadImage() on button btnUploadImage click event.
When i hit click btnUploadImage it generates following error on browser console
Error in FF
XML Parsing Error: no root element found Location:
https://localhost:44364/Admin/News/NewsCreate?handler=OnPostUploadImage
Line Number 1, Column 1:
Error in Chrome
jquery.min.js:2 POST
https://localhost:44364/Admin/News/NewsCreateMultipleSubmit?handler=OnPostUpLoadImage
400 (Bad Request)
event though path looks fine but it cant find it as per error message
#page
#model BookListRazor.Pages.Admin.News.NewsCreateModel
#{
ViewData["Title"] = "News Create";
Layout = "~/Pages/Shared/_LayoutAdmin.cshtml";
}
<div class="border container" style="padding:30px;">
<form method="post" enctype="multipart/form-data">
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<input hidden asp-for="News.NewsImage" />
<input id="fileName" hidden value="" />
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsHeading"></label>
</div>
<div class="col-10">
<input asp-for="News.NewsHeading" class="form-control" />
</div>
<span asp-validation-for="News.NewsHeading" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="News.NewsImage"></label>
</div>
<div class="col-10">
#*<input asp-for="News.NewsImage" type="file" class="form-control" id="NewsImage">*#
#*Photo property type is IFormFile, so ASP.NET Core automatically creates a FileUpload control *#
<div class="custom-file">
<input asp-for="NewsImageForUpload" class="custom-file-input form-control">
<label class="custom-file-label">Click here to change photo</label>
<input type="submit" value="Upload Image" asp-page-handler="OnPostUploadImage" id="btnUploadImage" />
</div>
</div>
<span id="imageStatus" class="text-danger"></span>
<span asp-validation-for="NewsImageForUpload" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-3 offset-3">
<input id="btnSave" type="submit" value="Create" class="btn btn-primary form-control" />
</div>
<div class="col-3">
<a asp-page="Index" class="btn btn-success form-control">Back to List</a>
</div>
</div>
</form>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/4.14.0/full/ckeditor.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSave").addClass("disable-button");
$('.custom-file-input').on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).next('.custom-file-label').html(fileName);
$("#fileName").val(fileName);
$("#btnSave").removeClass("disable-button");
});
if ($("#fileName").val() == "") {
//alert("Select Image...");;
}
});
</script>
</div>
#section Scripts{
<partial name="_ValidationScriptsPartial" />
<script>
$(function () {
$('#btnUploadImage').on('click', function (evt) {
console.log("btnUploadImage");
evt.preventDefault();
console.log("btnUploadImage after evt.preventDefault()");
$.ajax({
url: '#Url.Page("", "OnPostUploadImage")',
//data: new FormData(document.forms[0]),
contentType: false,
processData: false,
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});
});
});
</script>
}
.cs file CODE
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
return Page();
}
else
{
return Page();
}
}
public IActionResult OnPostUploadImage()
{
//Some code here
}
400 error because Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks. You don’t have to write any additional code. Antiforgery token generation and validation is automatically included in Razor Pages since i notice you have add FormTagHelper on page . So just modify your ajax to include token in header :
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
And configure the antiforgery service to look for the X-CSRF-TOKEN header :
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
Below article is for your reference :
Handle Ajax Requests in ASP.NET Core Razor Pages
And to post to OnPostUploadImage function in ajax , modify url to #Url.Page("", "UploadImage"):
$.ajax({
url: '#Url.Page("", "UploadImage")',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: false,
processData: false,
type: 'post',
success: function () {
alert('Uploaded by jQuery');
}
});

how to send form data by ajax from asp.net html page to c# code

I want to get from post value in my class method via ajax call
here is my html page
<form method="post">
<input type="text" name="text" />
<input type="email" name="email" />
<input type="file" name="file" />
<input type="date" name="date" />
<input type="submit" name="send" />
</form>
And this is my jquery code
$(document).ready(function () {
$('form').submit(function (e) {
var data = $(this).serializeArray();
var jsObj = {};
$.each(data, function (feild, value) {
jsObj[value.name] = value.value;
});
$.ajax({
url: "index.cs/addRow",
method: "post",
dataType: "json",
data: jsObj,
success : function(response){
console.log(response);
}
});
e.preventDefault();
});
And this is my c# code
these is the method where i want post form
[WebMethod]
public static void addRow(object form)
{
var stuff = form;
}
Your url parameter seems to be wrong (it should reference to ASPX page instead of code-behind file), also if the response is not JSON better to opt out dataType: 'json' definition. Try handling submit button's click event instead waiting for form submission like example below:
Markup (ASPX)
<form method="post">
<input type="text" name="text" />
<input type="email" name="email" />
<input type="file" name="file" />
<input type="date" name="date" />
<input id="submit" type="submit" name="send" />
</form>
jQuery
$('#submit').click(function () {
var formData = $('form').serializeArray();
$.ajax({
url: 'index.aspx/addRow',
method: 'POST',
data: formData,
success: function (response) {
// do something
},
// error handling
});
});
Note 1: $.each(data, function (feild, value) { ... }) is unnecessary because serializeArray() already contains form objects.
Note 2: If the form data is unchanged before POST, I suggest you using serialize() instead of serializeArray().
Related: Use AJAX to submit data from HTML form to WebMethod

Action creator is called but action is not dispatched

I have a component that successfully uses redux-form onSubmit to call an action creator. The creator performs an ajax call but the the action is never dispatched to save it to the store. I must have something messed up in the wiring of react-redux and redux-form, possibly in the binding of the action creator. I have read everything that I have found on Google and still can't find the problem. Any ideas? ( I have included redux-promise to handle the request promise, but it never makes it that far )
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import validate from '../utils/add_person_validation';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addPersonResponseAction } from '../actions/index';
import renderField from '../components/render_input_field';
// call the action creator - this part succeeds
const doSubmit = function(values) {
addPersonResponseAction(values);
};
let AddPersonContainer = (props) => {
const {
handleSubmit,
pristine,
reset,
submitting
} = props;
return (
<div className="row">
<form onSubmit={handleSubmit(doSubmit)} >
<div className="col-sm-6">
<fieldset>
<legend>Person Info</legend>
<div className="form-group">
<Field name="personFirstName" component={renderField} type="text" label="First Name" className="form-control" />
<Field name="personLastName" component={renderField} type="text" label="Last Name" className="form-control" />
<Field name="birthday" component={renderField} type="date" label="Birthday" className="form-control" />
<Field name="group" component={renderField} type="text" label="Group" className="form-control" />
</div>
</fieldset>
</div>
<div className="form-buttons-container">
<button className="btn btn-default form-button" type="submit" disabled={pristine || submitting}>Submit</button>
<button className="btn btn-default form-button" type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
</div>
);
};
const mapStateToProps = function({ addPersonResponse }) {
return { addPersonResponse };
};
const mapDispatchToProps = function(dispatch) {
return bindActionCreators( {addPersonResponseAction}, dispatch);
};
const form = reduxForm({ form: 'addPerson', validate: validate });
AddPersonContainer = connect(mapStateToProps, mapDispatchToProps)(form(AddPersonContainer));
export default AddPersonContainer;
/********************************************
* Action creator
**********************************************/
import axios from 'axios';
export const ADD_PERSON_RESPONSE = 'ADD_PERSON_RESPONSE';
export const addPersonResponseAction = (data) => {
const postURL = 'http://some-url/addperson';
const request = axios.post(postURL, { data });
return {
type: ADD_PERSON_RESPONSE,
payload: request
};
};
Redux wraps actions using mapDispatchToProps - but you are calling the unwrapped version by using the imported method.
// call the action creator - this part succeeds
const doSubmit = function(values) {
addPersonResponseAction(values); <------ Redux does not know anything about this
};
Try:
let AddPersonContainer = (props) => {
const {
handleSubmit,
pristine,
reset,
submitting
} = props;
const doSubmit = function(values) {
props.addPersonResponseAction(values); <----- Try this
}
return (
<div className="row">
<form onSubmit={handleSubmit(doSubmit)} >
<div className="col-sm-6">
<fieldset>
<legend>Person Info</legend>
<div className="form-group">
<Field name="personFirstName" component={renderField} type="text" label="First Name" className="form-control" />
<Field name="personLastName" component={renderField} type="text" label="Last Name" className="form-control" />
<Field name="birthday" component={renderField} type="date" label="Birthday" className="form-control" />
<Field name="group" component={renderField} type="text" label="Group" className="form-control" />
</div>
</fieldset>
</div>
<div className="form-buttons-container">
<button className="btn btn-default form-button" type="submit" disabled={pristine || submitting}>Submit</button>
<button className="btn btn-default form-button" type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
</div>
);
};
Because the function you are defining does not have access to props this gives a bit of a twist, so try refactoring it into the component definition.
This is a source of confusion because it is required to import the function so mapDispatchToProps can wrap it...but there is temptation to forget that the real action is in props, not the function itself. So I'm sure you are seeing results in the actual action function, but redux does not know because it is not wrapped in dispatch.

Resources