【发布时间】:2017-03-20 14:27:42
【问题描述】:
我正在使用 .Net Core 编写网页,最近我开始在我的网页中使用 jQuery。
部分视图显示在<div id="details"></div>
@model Program.Models.Device
<dl>
<dt>
@Html.DisplayNameFor(model => model.Alias)
</dt>
<dd>
@Html.DisplayFor(model => model.Alias)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Log)
</dt>
<dd>
<a data-toggle="modal" data-target="#logData">Open</a>
<div class="modal fade" id="logData" tabindex="-1" role="dialog" aria-labelledby="logDataLabel">
<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="myModalLabel">Log for @Html.DisplayFor(model => model.Alias)</h4>
</div>
<div class="modal-body">
@Html.TextAreaFor(m => m.Log, htmlAttributes: new { @class = "form-control", @id = "logTextArea", @placeholder = "Log is empty" })
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
@*This will be used to find the deviceID*@
@Html.HiddenFor(m => m.DeviceID, new { @class = "deviceID" })
<button type="button" class="btn btn-primary" id="save">Save changes</button>
</div>
</div>
</div>
</div>
</dd>
</dl>
为了大致了解我将使用该模式的内容,它是从我的一个称为设备的模型中更新日志。 textarea 将保存设备的日志,并且按预期工作。但是我想编写一个 JavaScript/jQuery 函数,从 textarea 中获取文本并将其传递给我的控制器中的函数:
.CS函数
public void UpdateLog(int id, string logText)
{
Device device = new Device { DeviceID = id, Log = logText };
_context.Devices.Attach(device);
_context.Entry(device).Property(x => x.Log).IsModified = true;
_context.SaveChanges();
}
JQuery 点击码
$('#details').on('click', '#save', function () {
var text = $("#logTextArea").val();
var id = $(this).siblings('deviceID').val(); //Getting deviceID
//Running C# method somehow?
});
如何以最佳方式获取 DeviceID? 编辑:查看模态代码和jQuery
此外,我发现要运行我的控制器函数,我需要一个 @Url.Action('<function name>', '<controller name>'),但是如何将变量传递给这样的函数,因为我现在将拥有函数所需的日志和 id?
编辑:
代码现在已经发生了一些变化,我现在得到了 deviceID(之前是对车辆 ID 的误解)。我唯一的问题是如何在我的 jQuery 点击代码中运行 .CS 函数并将两个参数传递给我的 .CS 函数。
谢谢!
【问题讨论】:
-
使用
@Html.TextAreaFor(m => m.Log)生成正确的视图并且只需为 ID 属性添加一个隐藏输入并在打开模式时使用 javascript 更新它。您需要展示如何生成<dd>元素以及如何处理点击事件 -
好的。我会在编辑中直接解决。
-
问题现已更新,对描述进行了编辑和细微更改。
-
为什么不将表单控件放在
<form>中?然后,您只需将按钮更改为type="button"。如果您想使用 ajax 发布值(以保持在同一页面上),那么它只是$('form').submit(function() { $.post(yourUrl, $(this).serialize(), function(response) { do something with the response }; });- 但不确定您要如何提交,或者在发布值后您想做什么 -
控制器方法签名是
public void UpdateLog(Device model),所以它的所有属性都绑定了
标签: javascript c# jquery asp.net-mvc .net-core