如何从jquery ajax表单调用动作方法?我创建以下代码,但是我的操作方法中的参数始终为null。注意:我已经添加了所有需要的脚本,例如quill.js,jquery.unobtrusive-ajax.js我有这个表格:
<form data-ajax="true" data-ajax-method="post" method="post">
<input type="text" name="postTitle" class="form-group" />
<div id="postData" name="postData"></div>
<br />
<button type="submit" class="btn btn btn-outline-dark" id="btnCreate">Create post</button>
</form>
以及此javascript和jquery脚本:QUILL:
<script>
var toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['link', 'image', 'video', 'formula'], // add's image support
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'] // remove formatting button
];
var quill = new Quill('#postData', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
</script>
呼叫后处理方法:
$(function () {
$('#btnCreate').click(function () {
var props = [{
"PostTitle": $("postTitle"),
"PostData": quill.root.innerHTML
}]
$.ajax({
url: '@Url.Action("Create", "Post")',
type: "POST",
data: { JSON.stringify(props) },
contentType: "application/json",
dataType: "json",
async: true,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc(e) {
console.log('Error!', e);
}
//console.log(postData);
});
});
我的操作方法:
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreatePost(string props) // here props is null
{
Post post = new Post { PostBody = props };
db.Posts.Add(post);
await db.SaveChangesAsync();
return View();
}
我认为每个输入元素都是从val()获得的;
$("postTitle").val() maybe