【问题标题】:Finding a class in a partialView (MVC) and passing variables to a function在 partialView (MVC) 中查找类并将变量传递给函数
【发布时间】: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">&times;</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('&lt;function name&gt;', '&lt;controller name&gt;'),但是如何将变量传递给这样的函数,因为我现在将拥有函数所需的日志和 id?

编辑:

代码现在已经发生了一些变化,我现在得到了 deviceID(之前是对车辆 ID 的误解)。我唯一的问题是如何在我的 jQuery 点击代码中运行 .CS 函数并将两个参数传递给我的 .CS 函数。

谢谢!

【问题讨论】:

  • 使用@Html.TextAreaFor(m =&gt; m.Log) 生成正确的视图并且只需为 ID 属性添加一个隐藏输入并在打开模式时使用 javascript 更新它。您需要展示如何生成&lt;dd&gt; 元素以及如何处理点击事件
  • 好的。我会在编辑中直接解决。
  • 问题现已更新,对描述进行了编辑和细微更改。
  • 为什么不将表单控件放在&lt;form&gt; 中?然后,您只需将按钮更改为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


【解决方案1】:

您需要进行 ajax 调用来发布该数据(假设您想留在同一页面中)。

您应该首先将表单控件包装在 &lt;form&gt; 标记中并添加 @Html.ValidationMessageFor(m =&gt; m.Log) 并将按钮更改为 type="submit" 以便在发布数据之前获得(并且可以检查)客户端验证。

<div class="modal-dialog" role="document">
    <div class="modal-content">
        ...
        <form>
            <div class="modal-body">
                @Html.HiddenFor(m => m.DeviceID)
                @Html.TextAreaFor(m => m.Log, htmlAttributes: new { @class = "form-control",     @placeholder = "Log is empty" })
                @Html.ValidationMessageFor(m => m.Log)
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </form>
    </div>
</div>

那么脚本将是

var url = '@Url.Action("UpdateLog")'; // assumes its the same controller that generated the view
$('#details').on('submit', 'form', function () { // handle to forms submit() event
    if (!$(this).valid()) {
        return; // cancel (the validation message will be displayed)
    }
    var data = $(this).serialize()
    $.post(url, data, function(response) {
        // do something with the response
    })
    return false; // cancel the default submit
});

然后您的 POST 方法将是 public ActionResult UpdateLog(int id, string log),但是要捕获服务器端验证,您应该创建一个装饰有必要验证属性的视图模型

public class DeviceLogVM
{
    public int ID { get; set; }
    [Required(ErrorMessage = "..")] // add StringLength etc as needed
    public string Log { get; set; }
}

这样方法就变成了

public ActionResult UpdateLog(DeviceLogVM model)

这样您就可以在保存之前检查ModelState 是否无效。另请注意,该方法应为ActionResult,以便您可以向客户端返回指示成功或其他情况的内容。

【讨论】:

    【解决方案2】:

    您可以像这样进行 ajax 调用:

    var data={
        logText:text,
        id :id
        };
    
        $.post('ControllerName/UpdateLog',data)
        .done(function(data){
        //When success return logic
        }).fail(function(xhr){
        //if request failed
        });
    

    【讨论】:

    • 在这个 sn-p 的某处有一个错误的语法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2010-09-09
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多