在我的項目中,我有一個用於創建文檔的主頁面,用戶可以在其中更改文檔的狀態DocumentsController
。如果狀態爲NEW
,則允許用戶將新設備(「部件」)添加到文檔。Ajax開始表單更新div
我的目標是在ajax表單上提交一個字符串到div#newDevice
。但是,html結果不會呈現在我的主視圖中,而是呈現爲鏈接..../PartsBoxes/CreatePartial
。
我該如何解決這個問題?
我的主頁部分:
<input type="button" value="Add a new box" id="addNewBoxButton" class="add_new_btn" />
<input type="button" value="Add box from db" id="addDBBoxButton" class="add_existent_btn" />
<hr />
<div id="newDevice"></div>
<hr />
<script>
$("#addNewBoxButton").on("click", function() {
var deviceId = 1;
$.get('@Url.Action("CreatePartial", "PartsBoxes")',{
deviceId: deviceId
},
function (data) {
$("#newDevice").html(data);
});
});
</script>
我的部分觀點:
@model NTStock.Models.BoxPartsViewModel
@{
ViewBag.Title = "Create";
}
@using (Ajax.BeginForm("CreatePartial", new AjaxOptions { UpdateTargetId = "newDevice" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.DocumentId)
<div class="form-group">
@Html.LabelFor(model => model.InternalName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.InternalName, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
@Html.ValidationMessageFor(model => model.InternalName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SerialNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.SerialNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SerialNumber, "", new { @class = "text-danger" })
</div>
</div>
//......///
<div class="form-group deviceManipulations">
@Html.LabelFor(model => model.DeinstallationDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DeinstallationDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DeinstallationDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save box" class="btn btn-default" />
</div>
</div>
</div>
}
和方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ContentResult CreatePartial(BoxPartsViewModel partsBox)
{
if (ModelState.IsValid)
{
//do something
}
return Content("string to return");
}
您可以發佈或突出的HTML您的按鈕和#newBox?我找不到它。 – Glubus
試着改變'return Content(「string to return」);'通過'return Json(new {data =「string to return」});'。同樣改變方法'CreatePartial'的返回類型爲'JsonResult' –
除了我得到的字符串相同的結果'{「data」:「返回的字符串}' – GeekyNuns