How to send data from react to Controller in ASP.NET MVC? - javascript

I am new to react. I am trying to build a CRUD application with React and .NET MVC. I am able to find the code for only getting content from controller, but not for posting.
Below is the code for getting data from controller:
var App = React.createClass({
getInitialState: function(){
return{data: ''};
},
componentWillMount: function(){
var xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
this.setState({ data: response.result });
}.bind(this);
xhr.send();
},
render: function(){
return(
<h1>{this.state.data}</h1>
);
}
});
Please provide me the code to send data from react to controller.
My data class:
public partial class EmployeeTable
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Designation { get; set; }
public long Salary { get; set; }
public string City { get; set; }
public string Country { get; set; }
}

As mentioned in the comments, sent the data using How to make a rest post call from ReactJS code?
Now create an action in your controller
[HttpPost]
public void GetInfo([FromBody]EmployeeTable data){
}

Related

Pass an Object from Angularjs to MVC controller and map to Class Object

I have an object in angularjs which I want to pass and map it to custom c# class in mvc controller. but whenever I am doing this class object is null completely.
$scope.Get = function () {
var EService = [{
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
}];
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
})
MVC Controller and Class:
[HttpPost]
public string Insert(ServicesMaster Service)
{
GIBCADBEntities gfientity = new GIBCADBEntities();
var record = "Sent"
return Json(record, JsonRequestBehavior.AllowGet);
} public class ServicesMaster
{
public string id { set; get; }
public string servicename { set; get; }
public string servicetype { set; get; }
public int? monthlyrental { set; get; }
public string serviceremarks { set; get; }
public byte servicestatus { set; get; }
public DateTime? activationdate { set; get; }
public DateTime? deactivationdate { set; get; }
}
The javascript variable/object "EService" is ok here, and when passing only the ServicesMaster object is created with null values and no data is mapped to it. I can send single string or any value from here but when sending a complete object its behaving like this.
You are passing an array from front end and fetching object from server end. just remove the "[" and "]" brace while set value to EService . Like :
$scope.Get = function () {
var Service = {};
Service = {
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
};
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
});
};
It should work now. :)

POSTing a complex Dictionary to Controller

I am attempting to post the following type to my controller.
Model
public class EmailNotificationSettings
{
public string EmailHost { get; set; }
public string EmailPassword { get; set; }
public int EmailPort { get; set; }
public string EmailSender { get; set; }
public string EmailUsername { get; set; }
public bool Enabled { get; set; }
public bool EnableUserEmailNotifications { get; set; }
public string RecipientEmail { get; set; }
public Dictionary<NotificationType, NotificationMessageContent> Message { get; set; }
}
NotificationType
public enum NotificationType
{
NewRequest,
Issue,
RequestAvailable,
RequestApproved,
AdminNote,
Test,
}
NotificationMessageContent
public class NotificationMessageContent
{
public string Subject { get; set; }
public string Body { get; set; }
}
Now all of the properties are part of my form except Message.
Here is how I plan to populate Message
View
<label for="newRequestSubject" class="control-label">New Request Subject</label>
<div>
<input type="text" class="form-control form-control-custom " id="newRequestSubject" name="newRequestSubject" value="#Model.Message.FirstOrDefault(x => x.Key == NotificationType.NewRequest).Value.Subject">
</div>
<label for="newRequestBody" class="control-label">New Request Body</label>
<div>
<input type="text" class="form-control form-control-custom " id="newRequestBody" name="newRequestBody" value="#Model.Message.FirstOrDefault(x => x.Key == NotificationType.NewRequest).Value.Body">
</div>
Javascript to Post
$('#save').click(function (e) {
e.preventDefault();
var newRequestObj = {
"Subject": $('#newRequestSubject').val(),
"Body": $('#newRequestBody').val()
};
var message = { 'NewRequest': JSON.stringify(newRequestObj) };
var $form = $("#mainForm");
var data = $form.serialize();
data = data + "&" +JSON.stringify(message);
$.ajax({
type: $form.prop("method"),
data: data,
url: $form.prop("action"),
dataType: "json",
success: function (response) {
// Do something
}
});
});
Now this is obviously the wrong way to do it as my Message property is not getting populated.
Any idea how I can POST to the controller and it update my model?
Controller if you want to see (Using NancyFX)
private Response SaveEmailNotifications()
{
var settings = this.Bind<EmailNotificationSettings>();
// settings.Message doesn't contain the new values
}
I cannot think of a way to make it work with pure HTML. The problem is you need to submit a control with the name "Message" that contain the data, then MVC mapping engine will map that control to the "Message" property of your model.
The best way I can think of is to use a JavaScript function (bound to the onsubmit event of the form) which collects the info as an array of objects and assign it to a variable called "Message" then serialize it with the rest of the form data and submit the form.

KendoUI treeview children are displayed as undefined

I have a treeview in kendoUI in which main nodes are calling into an mvc controller and that controller looks to whether there is an nullable id passed in and then uses a different model.
What I hit the url : http://localhost:2949/Report/GetReportGroupAssignments
I see this JSON
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4}
]
Now my mvc controller looks like this
public JsonResult GetReportGroupAssignments(int? id)
{
var model = new List<ReportGroup>();
var defModel = new List<ReportDefinition>();
try
{
if (id == null)
{
model = _reportService.GetReportGroups("en-us").ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
else
{
defModel = _reportService.GetReportDefinitions().Where(e=>e.ReportGroupID ==Convert.ToInt32(id)).ToList();
return Json(defModel, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Logger.Error(ex, "Error loading LoadReportList.");
return null;
}
}
My Kendo javascript looks like the following:
var serviceRoot = "/Report"; // "//demos.telerik.com/kendo-ui/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments", //"/LoadReportTree", // "/Employees",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,hasChildren: "Id"
}
}
});
var treeview = $("#treeview").kendoTreeView({
expanded: true,
dragAndDrop: true,
dataSource: homogeneous,
dataTextField: "ReportGroupName"
}).data("kendoTreeView");
Seems that the calls (which I discovered that children records have a "load" method that it called behind the seens, so basically I pass in the ID in order to get the data from the other model ( table in db)
(Id is mapped with automapper to ReportGroupID )
So when i click to the left of "Standard Rports" I am getting all of these children as undefined, How do I get these to show up properly?
Update: My ReportDefinition class:
public class ReportDefinition {
public override int Id { get; set; }
public string ReportKey { get; set; }
public string ReportName { get; set; }
public int? ReportNameResID { get; set; }
public string ReportDef { get; set; }
public int? ReportDefinitionResID { get; set; }
public string ReportAssembly { get; set; }
public string ReportClass { get; set; }
public int ReportGroupID { get; set; }
public int AppID { get; set; }
public int SortOrder { get; set; }
public bool IsSubReport { get; set; }
}
I think your problem is that the class ReportDefinition does not have a property called: ReportGroupName. That is why TreeView displays 'undefined'.
Try adding this Property to your ReportDefinition class like:
public class ReportDefinition {
// Other Properties
// I guess this property is missing
public string ReportGroupName { get; set; }
}

Passing JavaScript object to C#

I am trying to create a new row in a table I have hosted in Azure SQL Database. My front end is AngularJS with C# in .NET as the back end.
Here is my code from the front end passing the object:
var insertTicket = function (newTicket) {
return $http.post("http://localhost:50412/api/tickets", JSON.stringify(newTicket))
.then(function (response) {
console.log(response);
console.log("Insert Successful");
return;
});
And here is my backend code that receives the data and tries to add to the database:
[Route("api/tickets")]
public HttpResponseMessage Post(Ticket t)
{
TicketsRepository.InsertTicket(t);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
In TicketRepisitory:
public static void InsertTicket(Ticket tick)
{
var maxID = (from ticket in dataContext.Tickets
select ticket.id).Max();
var tick = new Ticket();
tick.id = maxID + 1;
dataContext.Tickets.Add(tick);
dataContext.SaveChanges();
}
And Here is my Ticket class:
public partial class Ticket
{
//Properties
public int id { get; set; }
public string title { get; set; }
public string customer { get; set; }
public string barcode { get; set; }
public string assignedTo { get; set; }
public string category { get; set; }
public string importance { get; set; }
public Nullable<System.DateTime> openDate { get; set; }
public Nullable<System.DateTime> dueDate { get; set; }
public Nullable<System.DateTime> closedDate { get; set; }
public string comments { get; set; }
public string condition { get; set; }
public Nullable<int> workHours { get; set; }
//Relationships
public Employee Employee { get; set; }
public Employee Employee1 { get; set; }
public Equipment Equipment { get; set; }
}
I think the issue is with Post() expecting a ticket object. I have tried searching for how to receive JSON data and use that for Ticket, but with out much luck.
My Problem is that I can not create a new row. No changes are reflected in my database.
You don't need to JSON.stringify your object when POSTing data with $httpin AngularJS, just pass the object itself as the second parameter, like this:
var insertTicket = function (newTicket) {
return $http.post("http://localhost:50412/api/tickets", newTicket)
.then(function (response) {
console.log(response);
console.log("Insert Successful");
return;
});
First there is no need to call JSON.stringify() method on newticket javascript object for second paramter of $http.post() method.
Then in the web api method write a parameter of type JObject with the name newTicket to receive the posted object, and use generic version of ToObject method to convert posted data to desired type. Don't forget to use [FromBody] attribute for the method parameter. the code for webapi looks like this:
[Route("api/tickets")]
public HttpResponseMessage Post([FromBody]JObject newTicket)
{
var t = newTicket.ToObject<Ticket>();
TicketsRepository.InsertTicket(t);
HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
return response;
}

Json invoke not working after moving to mvc5

Same code stopped working after move to mvc5. In the following code I am trying to get cities for a country which is chosen in a dropdownlist using json.
The View.cshtml
#Html.DropDownList("CountryId", (SelectList)ViewBag.Countries, " -- choose a country -- ", new { onchange = "CountryDDLChanged()", #class = "form-control" })
JavaScript file (a part of the code)
function CountryDDLChanged() {
var url1 = "../Country/GetCitiesByCountryId";
var countryid = $("#CountryId").val();
$.ajax({
type: "GET",
url: url1,
data: { countryId: countryid },
dataType: "json",
success: function (result) {
alert("yes");
},
error: function(req, status, error){
alert(error);
}
});
}
CountryController
public JsonResult GetCitiesByCountryId(int countryId)
{
JsonResult result = new JsonResult();
using (var db = new DBContext())
{
List<City> cities = db.Cities.Where(c => c.CountryId == countryId).ToList();
result.Data = cities;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
return result;
}
When I digg down in the code and debugging it. it generates this error.
he ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Why this works in MVC4 but not in MVC5? is it because of different version of EF?
how can I solve it?
UPDATED: Here is my Country Entithy and City :
[Table("Country")]
public class Country
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }
[StringLength(100)]
public string Name { get; set; }
public virtual List<City> Cities { get; set; }
public virtual List<Member> Members { get; set; }
public virtual List<MemberFee> MemberFees { get; set; }
}
[Table("City")]
public class City
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CityId { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
public virtual List<Member> Members { get; set; }
}

Categories

Resources