I'm trying to create a method to improve performance inserting in database. We work with asp net and use javascript/jquery/ajax on web.
First i created a function to get a form, but i want to use this method to different forms.
So my html is something like:
<form id="myForm">
<input type="hidden" name="TableId" value="@Model.TableId" />
<label for="Name"></label>
<input type="text" name="Name" id="Name" />
</form>
So the form go to controller, insert in database and the return of the controller is something like:
string json = JsonConvert.SerializeObject(object);
return new JsonResult(json);
and ajax:
$.ajax({
type: 'POST',
url: '/Controller/Action',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: myForm,
success: function (data) {
let jsonData = $.parseJSON(data);
// The next line is what i want to change
let myId = jsonData.TableId;
}
});
The issue is that the object returned by json will always have a different name because I want to use this same code in several forms.
For example:
If I use it in the Car table form, I need to get the primary key of the Car table, which would be CarId.
If I use it in the People table form, I need the value that will come from the object as data.PersonId.
I already know how to get the name of the primary key, but I can't concatenate it within ajax with the name of the object.
It would be something like:
let primaryKeyName = 'tableName' 'Id';
let primaryKeyValue = data. primaryKeyName;
I need to concatenate a string that i generate with the name of object.
CodePudding user response:
This should work using a mapping table:
const tableToKeyMap = {
Car: 'CarId',
People: 'PersonId'
}
function getJsonValue(data, tableName) {
let key = tableToKeyMap[tableName];
return data[key] || 'not found';
}
const dataFromJson = {
CarId: 'Toyota',
PersonId: 'Jane',
OtherId: 'foo'
}
console.log('Car => ' getJsonValue(dataFromJson, 'Car'));
console.log('People => ' getJsonValue(dataFromJson, 'People'));
console.log('Oops => ' getJsonValue(dataFromJson, 'Oops'));
Output:
Car => Toyota
People => Jane
Oops => not found