我想序列化html表单并通过ajax提交给我的服务器,但是在提交表单之前,我想重命名变量名并删除缩写部分,例如:BranchViewModels[0].
要更改:
将BranchViewModels[0].BranchName
更改为:BranchName
将BranchViewModels[1].AddressViewModel.AddressId
更改为AddressViewModel.AddressId
基本上,当我生成表单时,所有输入名称都呈现为数组,但是在提交表单之前,我想摆脱输入名称的数组部分(在此示例中为BranchViewModels [0]。)。
我已经解释了为什么要这样做here
我还为以下示例创建了jsfiddle。
function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serialize();
alert('I want to change the input names in this serialized form: \n\n' + serializedform );
// 1. iterated through serialized form
//
// remove BranchViewModels[i]. from the name, e.g.
// replace: BranchViewModels[0].BranchName
// with: BranchName
// 2. Submit the form
/* $.ajax({
url: "/my-server",
data: {branchViewModel: <-- serialized model},
dataType: 'json',
type: "POST"}); */
});
}
jQuery(document).ready(function($) {
updateBranch();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="return false;" novalidate="novalidate">
<div class="form">
<div class="form-group">
<label>Branch name</label>
<input class="form-control" data-val="true" id="BranchViewModels_0__BranchName" name="BranchViewModels[0].BranchName" type="text" value="branch 1">
</div>
<hr />
<div class="form-group">
<label>Branch location</label>
<div>
<input data-val="true" id="BranchViewModels_0__AddressViewModel_AddressId" name="BranchViewModels[0].AddressViewModel.AddressId" value="1956">
</div>
<div>
<input class="address-street-address" data-val="true" id="BranchViewModels_0__AddressViewModel_StreetAddress" name="BranchViewModels[0].AddressViewModel.StreetAddress" value="Wellington 6011, New Zealand">
</div>
</div>
<input type="button" class="btn btn-primary-action save-branch-button" value="Save">
</div>
</form>
答案 0 :(得分:2)
public class PushNotificationRepository : IPushNotificationRepository
{
IServiceScopeFactory _serviceScopeFactory;
public PushNotificationRepository(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
public void Add(PushNotification notification);
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<PushNotificationsContext>();
//other logic
}
}
}
答案 1 :(得分:0)
将序列化数据返回反序列化,然后更改为所需的内容,希望对您有所帮助。
console.log(deparam(serializedform));
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}