【发布时间】:2018-04-30 03:28:44
【问题描述】:
我是 React 新手。我正在尝试在 asp.net 中创建一个带有反应的表单。将表单数据从 reactjs 发布到 mvc asp.net 中的控制器时,数据未通过。我在下面分享了我的代码。请让我知道我必须进行哪些更改才能使其正常工作。
控制器:
[Route("InputEmployee")]
public void InputEmployee([FromBody]EmployeeTable Employee)
{
db.EmployeeTables.Add(Employee);
db.SaveChanges();
}
Reactjs 代码:
class InputValues extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const data = new FormData();
data.append = this.firstName.value;
data.append = this.lastName.value;
data.append = this.gender.value;
data.append = this.designation.value;
data.append = this.salary.value;
data.append = this.city.value;
data.append = this.country.value;
var xhr = new XMLHttpRequest();
xhr.open('post', this.props.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Do something on success
}
}
xhr.send(data);
}
render() {
return(
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="FirstName">First Name </label><br/>
<input id="FirstName" type="text" placeholder="Enter First Name" ref={(firstName) => this.firstName = firstName} />
<br/><br/>
<label htmlFor="LastName">Last Name: </label><br/>
<input id="LastName" type="text" placeholder="Enter Last Name" ref={(lastName) => this.lastName = lastName} />
<br/><br/>
<label htmlFor="Gender">Gender: </label><br/>
<input id="Gender" type="text" placeholder="Gender" ref={(gender) => this.gender = gender} />
<br/><br/>
<label htmlFor="Designation">Designation: </label><br/>
<input id="Designation" type="text" placeholder="Enter Designation" ref={(designation) => this.designation = designation} />
<br/><br/>
<label htmlFor="Salary">Salary: </label><br/>
<input id="Salary" type="number" placeholder="Enter Salary" ref={(salary) => this.salary = salary} />
<br/><br/>
<label htmlFor="City">City: </label><br/>
<input id="City" type="text" placeholder="Enter City" ref={(city) => this.city = city} />
<br/><br/>
<label htmlFor="Country">Country: </label><br/>
<input id="Country" type="text" placeholder="Enter Country" ref={(country) => this.country = country} />
<p>
<button type="submit">Submit</button>
</p>
</form>
</div>
);
}
};
ReactDOM.render(<InputValues url="api/Employee/InputEmployee" />,
document.getElementById('grid1'))
值未通过:
在追加修改后:
【问题讨论】:
-
@MarioNikolaus 嗨。非常感谢您修改的代码。你知道为什么数据没有通过吗?
-
不要为同一问题打开新问题。正如 James 指出的那样,代码在正确使用 append 函数时存在错误,我对其进行了更改,现在应该很好
-
@MarioNikolaus 好的。我尝试了修改后的代码。但是现在控制器函数根本没有被调用。我已经在运行代码的控制器函数中添加了数据流的屏幕截图。
-
在您的开发工具中提供请求的屏幕截图,以查看传递给后端服务的确切内容
标签: javascript asp.net asp.net-mvc reactjs asp.net-web-api