在局部视图(MVC)中查找类并将变量传递给函数

Finding a class in a partialView (MVC) and passing variables to a function

本文关键字:变量 函数 查找 视图 局部 MVC      更新时间:2023-09-26

我正在用。net Core写一个网页,我最近开始在我的网页中使用jQuery。

PartialView显示在<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>

给我一个大致的想法,我将使用模态,它是用于更新日志从我的一个模型称为设备。文本区将保存设备的日志,并且按预期工作。然而,我想写一个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(以前与vehicleID有误解)。我唯一的问题是如何运行。cs函数,并在两个参数传递到我的。cs函数在我的jQuery点击代码。

谢谢!

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

你应该开始包装你的表单控件在一个<form>标签和添加@Html.ValidationMessageFor(m => 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,这样您就可以向客户端返回一些指示成功或其他情况的内容。

您可以这样做ajax调用:

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