我对ajax有点小问题。所以首先我要告诉你我的行为。
形式:
<form id="QuestionForm">
@Html.TextBoxFor(model => model.Body, new { @class = "form-control", @placeholder = "Body" })
@Html.TextBoxFor(model => model.Text, new { @class = "form-control", @placeholder = "Text" })
</form>
这是我的脚本和ajax代码:
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
data: {data, @Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
这是我的控制器动作:
public JsonResult AddQuestion(SurveyQuestion model, int id)
{
SurveyQuestion question = new SurveyQuestion();
question.Body = model.Body;
question.CreatedOn = DateTime.Now;
question.ModifiedOn = DateTime.Now;
question.Priority = 0;
question.SurveyId = id;
question.Text = model.Text;
question.Type = QuestionType.Text;
_db.SurveyQuestions.Add(question);
_db.SaveChanges();
return Json(question, JsonRequestBehavior.AllowGet);
}
我没有填写代码的每一部分,其中一部分是硬编码的,因为我将在以后执行操作。但问题在于发送两件事。 如果我没有从控制器发送Id并删除Id,它会很好地发送序列化模型,但是如果我发送它们两者,它会得到Id,但它并没有将模型发送给他( text和body为null)。我该如何解决?
答案 0 :(得分:1)
你可以这样做:
$("#btnSubmit").click(function() {
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
// Add id like query string parameter like below
data: $('#QuestionForm').serialize() + '&id=' + @Model.Survey.Id,
success: function() {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
答案 1 :(得分:1)
将id作为查询字符串参数传递
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion?id=" + '@Model.Survey.Id',
data: {data, @Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
在控制器中,在参数
之前使用 FromUri 属性public JsonResult AddQuestion(SurveyQuestion model,[FromUri]int id)
{
SurveyQuestion question = new SurveyQuestion();
question.Body = model.Body;
question.CreatedOn = DateTime.Now;
question.ModifiedOn = DateTime.Now;
question.Priority = 0;
question.SurveyId = id;
question.Text = model.Text;
question.Type = QuestionType.Text;
_db.SurveyQuestions.Add(question);
_db.SaveChanges();
return Json(question, JsonRequestBehavior.AllowGet);
}
答案 2 :(得分:0)
您可以将ID放入网址
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion?id=@Model.Survey.Id",
data: {data},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
答案 3 :(得分:0)
试试这个,在post中传递多个参数,或者你可以使用querystring传递,如其他答案所示
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
data: {model : data, id: @Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
控制器
public ActionResult ActionName(SurveyQuestion model, int id)
{
Your Code .......
}