ASP.NET MVC 4 and Ext JS 4 Grid Panel - json

I am developing ASP.Net mvc 4 Application using EF .
This is Client/index.cshtml (Before Adding ExtJS)
#model IEnumerable<Proj.Client>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name_Clt)
</th>
<th>
#Html.DisplayNameFor(model => model.LName_Clt)
</th>
<th>
#Html.DisplayNameFor(model => model.Birthday_Clt)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name_Clt)
</td>
<td>
#Html.DisplayFor(modelItem => item.LName_Clt)
</td>
<td>
#Html.DisplayFor(modelItem => item.Birthday_Clt)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID_Client }) |
#Html.ActionLink("Details", "Details", new { id=item.ID_Client }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID_Client })
</td>
</tr>
}
</table>
I was following this blogpost , But I couldn't load data on it .
http://cincolabs.com/2012/04/10/asp-net-mvc-4-ext-js-4-gridpanel/
I created another ClientController .
public JsonResult GetUsers()
{
var entities = new Entities();
//What is important is to return the data as JSON.
return Json(entities.Clients.ToList(), JsonRequestBehavior.AllowGet);
}
Should I remplace this code .
public ActionResult Index()
{
var db = new Entities();
return View(db.Clients.ToList());
}
Another Question :
// Set up a model to use in our Store
Ext.define('Client', {
extend: 'Ext.data.Model',
fields: [
{ name: 'First_Name', type: 'string' },
{ name: 'Last_Name', type: 'string' },
{ name: 'Email', type: 'string' },
{ name: 'Date_Created', type: 'date', dateFormat: 'MS'}
]
});
var userStore = Ext.create('Ext.data.Store', {
model: 'Client',
proxy: {
type: 'ajax',
url: '/Examples/GetUsers',
reader: {
type: 'json',
root: 'users'
}
},
autoLoad: true
});
What does this mean "url: '/Examples/GetUsers'," !! Should I replace it in my case !!

Your first question is a bit vague. I never worked with Ext JS but from your posted code, it seems to me that it creates it own table using the GetUsers function. The first View you posted is an Index View that Visual Studio can automatically create that displays your data. If your Ext JS is creating the table, then I suggest you replace Index View with the appropriate code to call the table data. Then the method GetUsers should be renamed as Index.
Your question regarding /Examples/GetUsers should be the url to the controller method that saves your data (something like /Client/Save).

Related

React how to update json on right position?

I'm using react to display a table with data and inputs with the values.
My question is how to add a event handler inside my code?
And also how to update my JSON on the right position with the right value?
My JSON is a state named cards.
My JSON looks like this:
cards: [{
index: 0,
export: true,
fieldname: 'sub_nr',
caption: "Subnr",
tags: []
}, {
index: 1,
export: false,
fieldname: 'address1',
caption: "Adress",
tags: []
}, {
index: 2,
export: false,
fieldname: 'post_code',
caption: "zipcode",
tags: []
}]
My code generates this:
This is my react code:
const Card = props => {
return props.connectDropTarget(
<tbody>
{ props.connectDragSource(
<tr className="pt-1 pb-1">
<td style={{textAlign: "center"}}>
<input type="checkbox" checked={props.export} />
</td>
<td>
<input type="text" value={props.caption} />
</td>
<td>
<input type="text" value={props.fieldname} />
</td>
<td>
<input type="option" />
</td>
<td style={{textAlign: "center"}}>
<i class="fa fa-arrows" aria-hidden="true"></i>
</td>
</tr>
) }
</tbody>
);
}
const typeCard = Symbol.for('##Type::Card');
const specTarget = {
drop(props) {
return {
index: props.index,
indexnr: props.indexnr,
};
}
};
const specSource = {
beginDrag(props) {
return {
index: props.index,
};
},
endDrag(props, monitor) {
if (!monitor.didDrop()) {
return;
}
const source = monitor.getItem();
const target = monitor.getDropResult();
if (source.index === target.index) {
return;
}
props.moveCard(source.index, target.indexnr);
}
};
const collectTarget = connect => ({
connectDropTarget: connect.dropTarget(),
});
const collectSource = (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
});
const CardWithDnD = ReactDnD.DropTarget(typeCard, specTarget, collectTarget)(
ReactDnD.DragSource(typeCard, specSource, collectSource)(Card)
);
class App extends React.Component {
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
cards: [{
index: 0,
export: true,
fieldname: 'sub_nr',
caption: "Subnr",
tags: []
}, {
index: 1,
export: false,
fieldname: 'address1',
caption: "Adress",
tags: []
}, {
index: 2,
export: false,
fieldname: 'post_code',
caption: "Postcode",
tags: []
}
]
};
}
moveCard (index, indexnr) {
const { cards } = this.state;
const sourceCard = cards.find(card => card.index === index);
const sortCards = cards.filter(card => card.index !== index)
sortCards.splice(indexnr, 0, sourceCard);
Object.keys(sortCards).forEach(function(nr) {
sortCards[nr].index = parseInt(nr, 10);
});
this.setState({ cards: sortCards });
console.log(this.state.cards);
}
render() {
const { cards } = this.state;
return (
<table className="offset-2 col-8">
{ cards.map((card, i) => (
<CardWithDnD
key={card.index}
indexnr={i}
moveCard={this.moveCard}
{...card}
/>
)) }
</table>
);
}
}
ReactDOM.render(
<ReactDnD.DragDropContextProvider backend={ReactDnDHTML5Backend}>
<App />
</ReactDnD.DragDropContextProvider>,
document.getElementById('root'),
);
I'm already able to update the index on dragging the table row, but I also want to update the Json fieldname and caption when I change the input.
How to do that?
Create a handleChange(event) function and assign it to get the input fields you want to get or set the input from. Then use the passed value inside (event.target.value) and update your state using this.setState() method inside the handleChange(event) function
Check this link for clarification

How to display other component in one other *ngFor

I have this table in html
<form [formGroup]="myform" (ngSubmit)="submit()" >
<tbody>
<tr class="group" *ngFor="let item of products;">
<td>
<div>
{{item.product_type_id}}
</div>
</td>
<td>{{item.product_id}}</td>
</tr>
</tbody>
<form>
I have this products in ts code: this.products = this.ps.getProduct(); that getall my product.
Product have this property
export class Products {
product_id: number;
product_type_id: number;
prodcttype: ProductType[];}
When I create a product, I get my productType from ws, like this
this.pts.getAllProductType().subscribe(
producttype => {
this.producttype = producttype;
}
);
Product Type have this property
export class ProductType {
product_type_name: string;
description: number;
default_price: number;
product_type_id: string;}
I want to display in html in this {{item.product_type_id}} --> {{item.product_type_name}}
At the moment this doesn't function because product_type_name
not found in Products
ts code:
this.myform= new FormGroup({
'invoice_number': new FormControl('', [Validators.required, Validators.nullValidator]),
'invoice_date': new FormControl('', Validators.required),
'client_id': new FormControl('', Validators.required),
'products': this.fb.array([])
});
ngOnInit() {
this.products = this.ps.getProduct();
console.log(this.products)
this.pts.getAllProductType().subscribe(
producttype => {
this.producttype = producttype;
}
);
submit() {}
}
service producttype
public getAllProductType(): Observable<ProductType[]> {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.getAllProductType), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(producttype => {
return new ProductType(producttype);
});
}
});
}
service product
private products: Products[] = [];
getProduct() {
return this.products;
}
Can you suggest me any solution, how to solve it?
From the detail question in the comments I would suggest you to make a new function in the component which would filter productType and provide you with productName. Code for same is as follow:
Add following function in componnent
getProductName(productTypeId: string) {
const [filteredProdType] = this.producttype.filter(pt => pt.product_type_id== productTypeId);
return filteredProdType.product_type_name;
}
And change your template to
<form [formGroup]="myform" (ngSubmit)="submit()" >
<tbody>
<tr class="group" *ngFor="let item of products;">
<td>
<div>
{{item.product_type_id}}
</div>
</td>
<td>{{getProductName(item.product_type_id)}}</td>
</tr>
</tbody>
<form>
this will fetch the product name of item by using product_type_id.
Hope this help. Add comments if further help needed.

Knock out foreach binding from object array

I am new in knockout. I want to make the list of students.
I have attached the list structure which returned from MVC as an image, Click here to view.
Js code:
var employeeListViewModel = {};
var employeeViewModel = {
id: "",
name: ko.observable("neenu"),
age: ko.observable(),
email: ko.observable(),
department: ko.observable(),
address: {
address1: ko.observable(),
city: ko.observable(),
State: ko.observable()
},
};
var employeePageViewModel = {
employee: employeeViewModel,
employees: employeeListViewModel
};
var dataSource = {
getemployees: function () {
getData("Employee/GetEmployees").then((data) => {
var result = ko.mapping.fromJS(data.data);
employeeListViewModel = result();
console.log(employeeListViewModel);
});
},
init: function () {
this.getemployees();
}
}.init();
ko.applyBindings(employeePageViewModel);
Html code:
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody data-bind="foreach: employees">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Id"></td>
</tr>
</tbody>
When I run this page ,It is neither displaying any error nor displaying data. Please help.
1) employeeListViewModel must be a ko.observableArray()
2) also when getting the result from your getData function just set the observableArray to the list:
employeeListViewModel(data.data); //assuming data.data is a [].
3) ko.mapping.fromJS(data.data); can be removed

Passing an ID from Razor view to Controller

In a view of type List I'm trying to pass the id (which is an eMail in this case) of the item from the view to an actionResult in the controller: I used the following code():
#Html.ActionLink("Contact", "CreateMessage", "Member", new { id = item.eMail })
I get a null reference because the id passed is null.
Here's the view which works just fine and the id in it isn't null:
#model IEnumerable<Mutuelle.Domain.Entities.Adherent>
#{
ViewBag.Title = "lister";
}
<h2>Liste des adhérents</h2>
<table class="table">
<tr>
<body style="overflow:scroll;">
<th>
#Html.DisplayNameFor(model => model.dateOfBirth)
</th>
<th>
#Html.DisplayNameFor(model => model.address)
</th>
<th>
#Html.DisplayNameFor(model => model.phoneNumber)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.dateOfBirth)
</td>
<td>
#Html.DisplayFor(modelItem => item.address)
</td>
<td>
#Html.DisplayFor(modelItem => item.phoneNumber)
</td>
<td>
#Html.ActionLink("Contacter", "CreateMessage", "MembreComite", new { id = item.eMail })
</td>
</tr>
}
</table>
Here's the controller:
public ActionResult CreateMessage(string id)
{
Message message = new Message();
return View(message);
}
[HttpPost]
public ActionResult CreateMessage(Message message, string id)
{
if (ModelState.IsValid)
{
AMDMService service = new AMDMService();
Member member = service.GetMemberByeMail(id);
message.member = member;
message.adherentId = id;
member.listMessages.Add(message);
return RedirectToAction("listeMessages");
}
return View(message);
}
When you use routeValues like new { id = item.eMail } in your ActionLink, then you always should provide value for html attributes, which mostly used for styling your link, so if you don't want to style your link then you pass null otherwise you pass something like that new { #class = "btn btn-rounded btn-blue" }). So your code for ActionLink should look like this if you don't want to style your link:
#Html.ActionLink("Contact", "CreateMessage", "Member", new { id = item.eMail }, null);
Also you can replace #Html.ActionLink helper with #Url.Action helper like below:
Contact

use a model as IEnumerable and static in same view

Am trying to put together a view where it will generate a detail list from a table through code first and a strongly typed view but also allow the user to input data into through the model into the table.
So the first part is:
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Gender)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.GenderID }) |
#Html.ActionLink("Details", "Details", new { id = item.GenderID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.GenderID })
</td>
</tr>
}
</table>
The next part to enter a new gender would be:
<div>#Html.LabelFor(model => model.Gender)</div>
<div>#Html.EditorFor(model => model.Gender, new { htmlAttributes = new { #class = "div-form-control", id = "LkUpGender" } })</div>
<div>#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })</div>
The problem is the first part requires:
IEnumerable<OrwellFrontEnd.LkUpModels.vwLkUpGender>
But the second part seems to not work with that and require:
OrwellFrontEnd.LkUpModels.vwLkUpGender
How can I make this work?