我有一个主视图,该主视图在按下按钮后会触发部分视图。最初,我只是想让部分视图将数据返回给用户,但是我决定向控制器添加一个额外的POST
,但是,它是与页面显示不同的模型类型。
主视图
@model List<Info>
@{
ViewBag.Title = "InfoPage";
}
</br></br></br></br>
<div id="DetailDIV"></div>
<table class="table table-bordered table-responsive table-hover">
<tr>
<th>Info</th>
<th>stuff</th>
<th>more info</th>
<th>Created</th>
</tr>
@foreach (var item in Model)
{
<tr onclick="DetailedView(@item.Info_ID)">
<td>
@item.InfoTitle
</td>
<td>
@item.stuff
</td>
<td>
@item.moreInfo
</td>
<td>
@item.Create_Date
</td>
</tr>
}
</table>
function DetailedView(id) {
var url = '@Url.Action("GetInfoModal", "Info", new { Info_ID = "replaceToken" })'.replace("replaceToken", id);
$("#DetailDIV").load(url, function (responseTxt, statusTxt, xhr) {
// debugger;
if (statusTxt == "success") {
$('body #DetailModal').modal('show');
}
if (statusTxt == "error") {
console.log("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}
</script>
局部视图
@model Info
<!-- Modal -->
<div class="modal fade" id="DetailModal" tabindex="-1" role="dialog" aria-labelledby="DetailModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="DetailModalLabel">@Model.InfoTitle</h4>
</div>
<div class="modal-body">
<div>
<div class="col-md-6">
more info stuff...
</div>
<div class="col-md-6">
even more info stuff
</div>
<div width="100%">
<button id="QuestionButton" type="button" class="btn btn-primary" onclick="OpenQuestionBox()">Message</button>
<div id="QuestionBox" hidden>
<textarea id="QuestionContent" placeholder="Question Content"></textarea>
<button type="button" class="btn btn-primary" onclick="SendQuestion(@Model.info_ID)">Send Message</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Close</button>
@*<button type="submit" class="btn btn-primary">Save Changes</button>*@
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function OpenQuestionBox() {
$('#QuestionButton').hide();
$('#QuestionBox').show();
}
}
</script>
如您所见,详细信息模式中的模型为Info
,但是如果用户有任何问题,我只想在问题框中发送一些字符串。我也想跳过Info_ID
,以便能够将问题与正确的数据联系起来。我试图使用AJAX,就像我在主视图中所做的一样,但是得到了.Replace doesnt exist
,这让我开始思考是否有更好或更简单的方法可以做到这一点。
这是我尝试过的ajax:
$.ajax({
url: '@Url.Action("SendQuestion", "Info", new { content = "Content~text", InfoID = "Info_id" })'.Replace("Content~text", text).Replace("Info_id", id),
type: 'POST',
dataType: 'json',
data: {
content: text,
Info_id: id
},
success: function (result) {
alert(result);
}
});
答案 0 :(得分:1)
您可以这样做:
var QuestionData = {
content = $("#QuestionContent").val(),
InfoID = $("#Info_id").val()
};
$("#SendQuestion").click(function () {
$.ajax({
url: 'Info/SendQuestion',
type: 'POST',
dataType: 'json',
data: QuestionData,
success: function (result) {
alert(result);
}
});
});