RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-242801

Андрей's questions

Martin Hope
Андрей
Asked: 2020-03-13 01:37:38 +0000 UTC

new() 类型约束

  • 0

我有课车:

public class Car
{
    public int Id { get; set; }
    [Range(1, 1000000000, ErrorMessage = "\"{0}\" должна иметь значение между {1} и {2}")]
    [Required(ErrorMessage = "\"{0}\" обязательна для заполнения")]
    [Display(Name = "Цена")]
    public int Price { get; set; }

    [Range(1, 1000000000, ErrorMessage = "\"{0}\" должно иметь значение между {1} и {2}")]
    [Required(ErrorMessage = "\"{0}\" обязательно для заполнения")]
    [Display(Name = "Количество на складе")]
    public int Count { get; set; }

    public int EquipmentId { get; set; }
    public virtual Equipment Equipment { get; set; }

    public virtual ICollection<Order> Orders { get; set; }
}

并且有一个泛型类型接口,从该类继承,然后在另一个具有业务逻辑的类中使用该类的方法。

界面:

public interface IModelSort<T> where T : new()
{
    IEnumerable<T> GetModelSort<K>(IEnumerable<T> model, Func<T, K> predSort, bool asc);
}

班级:

public IEnumerable<T> GetModelSort<K>(IEnumerable<T> model, Func<T, K> predSort, bool asc)
{
    return asc ? model.OrderBy(predSort) : model.OrderByDescending(predSort);
}

方法:

public IEnumerable<T> GetSortedModel<T, K>(IEnumerable<T> model, Func<T, K> predSort, bool asc) where T : new()
{
    return new ModelSort<T>().GetModelSort(model, predSort, asc).ToList();
}

最初,而new()不是class. 但后来我读到了 new() 类型约束并决定尝试替换它。但正如我对这个限制的考虑,类型参数必须有一个不带参数的公共构造函数。但是我的班级根本没有构造函数。那么为什么在 new() 这样的约束下一切都对我有用?也许如果该类根本没有构造函数,那么它意味着某种根本不可见的默认值?

c#
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-02-05 20:55:31 +0000 UTC

将类列表转换为列表 T

  • 1

有问题。我有一堂课First。我正在尝试在模板 T 上编写一个方法,当我尝试返回 List 时出现错误:

“IEnumerable”不包含“ToList”的定义,并且最佳扩展方法重载“Enumerable.ToList(IEnumerable)”需要“IEnumerable”类型的接收器

我不明白为什么会这样。毕竟 Enumerable 有 toList 为什么不能选择我要输出的类型呢?还是没有显式类型转换就不可能?

这是我的代码示例:

class Program
{
    List<First> fl = new List<First>();

    static void Main(string[] args)
    {
    }

    public List<T> GetF<T>() where T : First
    {
        return fl.Where(a => a is T).ToList<T>();
    }
}

public class First
{
    public int Age { get; set; }
}
c#
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-23 23:51:41 +0000 UTC

通过值将引用参数传递给方法

  • 1

microsoft 文档说,如果您按值传递引用类型,那么实际上引用的副本将传递给该方法。那为什么,如果你在方法中改变了这个参数,然后回到main,值仍然改变?如果传输的是链接本身而不是其副本,那么就很清楚了。

c#
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-08-21 18:38:44 +0000 UTC

在 ASP.NET Web 窗体应用程序中使用 __doPostBack

  • 1

我正在尝试使用 __doPostBack 函数,但出现错误。在服务器端,我只有页面加载。在客户端,代码如下:

<script type="text/javascript">
    $(document).keydown(function (e) {
        if (e.keyCode === 13) {
            __doPostBack('myTrg', '');
        }
    });
</script>

但是当我按下回车键时,这是客户端出现的错误。

Home.aspx:39 未捕获的 ReferenceError:__doPostBack 未在 HTMLDocument 中定义。(Home.aspx:39) 在 HTMLDocument.dispatch(jquery.min.js:2) 在 HTMLDocument.v.handle(jquery.min.js:2)

这是我将 jquery 连接到页面的方式

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

我究竟做错了什么?

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-03-10 23:11:32 +0000 UTC

一行中的元素排列[关闭]

  • -1
关闭 这个问题是题外话。目前不接受回复。

寻求调试帮助的问题(“为什么这段代码不起作用? ”)应该包括期望的行为、具体的问题或错误,以及在问题中重现它的最少代码。没有明确描述问题的问题对其他访问者毫无用处。请参阅如何创建一个最小的、独立的和可重现的示例。

3年前关闭。

改进问题

有一个页面,您需要在该页面上将多个元素排列成一行。我做到了,但出于某种原因,在两种不同的情况下,我采取了不同的做法,我不明白为什么。

选项1:

    <div class="row">
                <div class="col-sm-4">
                    <div class="form-group">
                        @Html.Label("С", new { @style = "margin-right: 5px" })
                        <input type="date" />
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        @Html.Label("По", new { @style = "margin-right: 5px" })
                        <input type="date" />
                    </div>
                </div>
            </div>

4 个元素排成一排。但是有一个例子不适合相同的方法。选项 2:

    <div class="row">
                <div class="col-sm-10">
                    <div class="row">
                        <div class="col-sm-4">
                            <div class="form-group" style="margin-right: 10px">
                                @Html.RadioButton("Proceeds", "Seller", true)
                                @Html.Label("По продавцу")
                            </div>
                        </div>
                        <div class="col-sm-8">
                            <div class="form-group">
                                @Html.DropDownList("sellerList", Enumerable.Empty<SelectListItem>(), new { @style = "display: inline-block", @class = "form-control" })
                                @Html.CheckBox("allSeller")
                                @Html.Label("По каждому")
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-sm-4">
                            <div class="form-group" style="margin-right: 10px">
                                @Html.RadioButton("Proceeds", "Auto", false)
                                @Html.Label("По автомобилю")
                            </div>
                        </div>
                        <div class="col-sm-8">
                            <div class="form-group">
                                @Html.DropDownList("autoList", Enumerable.Empty<SelectListItem>(), new { @style = "display: inline-block", @class = "form-control" })
                                @Html.CheckBox("allAuto")
                                @Html.Label("По каждой")
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-2">
                    <div class="row">
                        <div class="col-sm-12">
                            <input type="button" value="Выручка" class="btn btn-primary btn-block" style="height: 80px" />
                        </div>
                    </div>
                </div>
            </div>

在这种情况下,必须设置下拉列表,"display: inline-block"否则下一个标签将转移到下一行。这是为什么?如果我做错了什么,你能告诉我吗?

这是来自浏览器的代码:

<div class="row">
    <div class="col-sm-8">
        <div id="headTableProceeds">
            <table class="table table-bordered" style="margin: 0; table-layout: fixed">
                <thead>
                    <tr>
                        <th id="sel" style="display: none">Продавец</th>
                        <th id="auto" style="display: none">Автомобиль</th>
                        <th id="proceeds" style="display: none">Выручка</th>
                    </tr>
                </thead>
            </table>
        </div>
        <div id="bodyTableProceeds" class="container">
            <table class="table table-bordered">
                <tbody></tbody>
            </table>
        </div>

        <div class="row">
            <div class="col-sm-12">
                <label for="">Фильтры детализации:</label>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-12">
                <input id="Date" name="Date" type="checkbox" value="true" /><input name="Date" type="hidden" value="false" />
                <label for="">По дате</label>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-4">
                <div class="form-group">
                    <label for="" style="margin-right: 5px">С</label>
                    <input type="date" disabled />
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label for="" style="margin-right: 5px">По</label>
                    <input type="date" disabled />
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-10">
                <div class="row">
                    <div class="col-sm-4">
                        <div class="form-group" style="margin-right: 10px">
                            <input checked="checked" id="Proceeds" name="Proceeds" type="radio" value="Seller" />
                            <label for="">По продавцу</label>
                        </div>
                    </div>
                    <div class="col-sm-8">
                        <div class="form-group">
                            <select class="form-control" id="sellerList" name="sellerList" style="display: inline-block"></select>
                            <input id="allSeller" name="allSeller" type="checkbox" value="true" /><input name="allSeller" type="hidden" value="false" />
                            <label for="">По каждому</label>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-4">
                        <div class="form-group" style="margin-right: 10px">
                            <input id="Proceeds" name="Proceeds" type="radio" value="Auto" />
                            <label for="">По автомобилю</label>
                        </div>
                    </div>
                    <div class="col-sm-8">
                        <div class="form-group">
                            <select class="form-control" disabled="disabled" id="autoList" name="autoList" style="display: inline-block"></select>
                            <input disabled="disabled" id="allAuto" name="allAuto" type="checkbox" value="true" /><input name="allAuto" type="hidden" value="false" />
                            <label for="">По каждой</label>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-sm-2">
                <div class="row">
                    <div class="col-sm-12">
                        <input type="button" value="Выручка" class="btn btn-primary btn-block" style="height: 80px" />
                    </div>
                </div>
            </div>
        </div>

        <table style="display: none" id="equipTable" class="table table-bordered">
            <thead>
                <tr>
                    <th>Двигатель</th>
                    <th>Мощность</th>
                    <th>Год выпуска</th>
                    <th>Тип привода</th>
                    <th>КПП</th>
                    <th>Кузов</th>
                    <th>Максимальная скорость</th>
                    <th>Вес</th>
                    <th>Бак</th>
                    <th>Цвет</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td></td>
                </tr>
            </tbody>
        </table>
    </div>
    <div style="display: none" class="col-sm-4">
        <img id="autoPic" class="img-responsive" src="/Content/auto.jpg" />
    </div>
</div>

在此处输入图像描述

html
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-02-13 18:32:16 +0000 UTC

连续执行 2 组警报

  • 0

连续执行两个甜蜜警报存在问题。该页面显示一个包含车辆列表的页面。通过双击该行,会出现一个甜蜜的警报,询问用户他是否真的想下订单。如果用户单击确定,则将 ajax 请求发送到服务器并执行一些购买汽车的逻辑。然后它返回必要的信息给我,如果一切都成功,那么我在表格中查找我购买的汽车,仓库中的数量列,然后将数字减一。之后,我又调用了 1 个套件警报,告诉用户他已成功下订单。例如,如果仓库中的汽车数量为 0,那么将在套件警报中向用户显示相应的消息。所以当你第一次启动应用程序时,一切都会成功,并且在不重新启动应用程序的情况下进一步尝试,一切正常,但最后一个(成功或不成功)套件警报不会弹出。我尝试将这些警报拉入一个单独的函数并使用 setInterval 调用它们,至少延迟 100 毫秒,然后一切正常。请告诉我这是怎么回事?为什么它不能立即工作?

这是我的代码,没有延迟:

$('tbody').dblclick(function (e) {
        swal({
            title: 'Оформление заказа',
            text: 'Вы уверены что хотите оформить заказ?',
            type: "info",
            showCancelButton: true
        },
            function (isConfirm) {
                if (isConfirm) {
                    var carId = $(e.target).closest('tr').attr('id');

                    $.ajax({
                        type: "POST",
                        url: "/Home/CarPurchase",
                        data: {
                            "carId": carId
                        },
                        success: function (response) {
                            if (response.result) {
                                var count = $(".context-menu tbody tr[id=" + response.id + "] td[id=count]");
                                count.text(count.text() - 1);
                                swal({
                                    title: "Заказ оформлен",
                                    type: "success"
                                });
                            }
                        },
                        error: function (xhr) {
                            swal({
                                title: xhr.responseText,
                                type: "warning"
                            });
                        }
                    });
                }
            }
        );
    });



   $('tbody').dblclick(function (e) {
            swal({
                title: 'Оформление заказа',
                text: 'Вы уверены что хотите оформить заказ?',
                type: "info",
                showCancelButton: true
            },
                function (isConfirm) {
                    if (isConfirm) {
                        var carId = $(e.target).closest('tr').attr('id');

                        $.ajax({
                            type: "POST",
                            url: "/Home/CarPurchase",
                            data: {
                                "carId": carId
                            },
                            success: function (response) {
                                if (response.result) {
                                    var count = $(".context-menu tbody tr[id=" + response.id + "] td[id=count]");
                                    count.text(count.text() - 1);
                                    setTimeout(Success, 100);
                                }
                            },
                            error: function (xhr) {
                                swal({
                                    title: xhr.responseText,
                                    type: "warning"
                                });
                            }
                        });
                    }
                }
            );
        });

function Success() {
        swal({
            title: "Заказ оформлен",
            type: "success"
        });
    }
javascript
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-28 19:33:27 +0000 UTC

使用 jquery 上下文菜单获取行 ID

  • 1

在 asp.net mvc 应用程序中,我使用 jquery 上下文菜单库。这是我的代码:

$.contextMenu({
            selector: '.context-menu',
            build: function ($trigger, e) {
                return {
                    callback: function (key, options) {

                    },
                    items: {

                    }
                };
            }
        });

删除了额外的代码。

这是我的看法:

<table class="table table-bordered">
    <thead>
        <tr>
            <th>
                @Html.ActionLink("Марка", "Index", new { sortOrder = ViewBag.MarkSort })
            </th>
            <th>Модель</th>
            <th>
                @Html.ActionLink("Цена", "Index", new { sortOrder = ViewBag.PriceSort })
            </th>
            <th>Количество на складе</th>
        </tr>
    </thead>
    <tbody class="context-menu">
        @foreach (var item in Model)
        {
            @Html.Partial("_Car", item)
        }
    </tbody>
</table>

这是我的局部视图,它被调用来渲染表中的行:

@model AutoStore.Domain.Core.Car

<tr id="@Model.Id">
    <td>@Html.DisplayFor(item => item.Mark.MarkName)</td>
    <td>@Html.DisplayFor(item => item.CarModel.ModelName)</td>
    <td>@Html.DisplayFor(item => item.Price)</td>
    <td>@Html.DisplayFor(item => item.Count)</td>
</tr>

部分可见,我挂断了 tr (字符串)上的记录 ID。所以。当我调用上下文菜单进行进一步编辑时,我想考虑我单击的行的 id。

我找不到如何提取特定行的特定 ID。但是有一个选项可以拉出我单击的 id tds,但在这种情况下,ids 将不得不挂在所有 tds 上,我还不想这样做,请告诉我如何拉出整行的id。PS。如果点击的 td 的 id 是使用 build 中的 e 参数提取的e.target.id

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-28 17:37:49 +0000 UTC

发送ajax请求时的模型验证

  • 1

在 asp.net mvc 上有一个站点。有一个页面添加了 2 个字段。第一个字段可以在 EditorFor 中输入或从下拉列表中选择,第二个字段必须输入新的。

在此处输入图像描述

例如,如果下拉列表被禁用。

@Html.DropDownListFor(i => i.Mark.Id, ViewBag.marks as SelectList, new { @id = "exMark", @class = "form-control", @disabled = "disabled"* })
                    @Html.ValidationMessageFor(i => i.Mark.MarkName, "", new { @class = "text-danger" })

然后在服务器上的 ModelState 中有 2 个字段用于验证,这两个字段都应该是 EditorFor。

在此处输入图像描述

然后,如果我填写它们,则验证将通过。

但是,如果我禁用了 EditorFor 并且选择了下拉列表中的第一个字段,并且在这种情况下假定不应感知 EditorFor 中第一个字段的值。然后由于某种原因,ModelState 中的服务器上的所有 3 个字段都用于验证,事实证明,即使我输入了两个字段并且禁用的 EditorFor 保持为空,验证也将不起作用,因为它也被考虑在内。为什么会这样?就模型验证而言,禁用对 EditorFor 不起作用。

如果输入字段被禁用,这是一个屏幕:

在此处输入图像描述

请告诉我可能出了什么问题?

c#
  • 2 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-28 01:12:17 +0000 UTC

将模型从 ajax 请求传递到操作

  • 1

将数据从 ajax 请求传递到控制器操作时存在问题。

这是我的模型:

public class Mark
{
    public int Id { get; set; }
    [Required]
    [Display(Name = "Марка")]
    public string MarkName { get; set; }

    public virtual ICollection<CarModel> CarModels { get; set; }
    public virtual ICollection<Car> Cars { get; set; }

    public Mark()
    {
        CarModels = new List<CarModel>();
        Cars = new List<Car>();
    }
}

public class CarModel
{
    public int Id { get; set; }
    [Required]
    [Display(Name = "Модель")]
    public string ModelName { get; set; }

    public int MarkId { get; set; }
    public virtual Mark Mark { get; set; }

    public virtual ICollection<Equipment> Equipments { get; set; }
    public virtual ICollection<Car> Cars { get; set; }

    public CarModel()
    {
        Equipments = new List<Equipment>();
        Cars = new List<Car>();
    }
}

以下是我的部分观点:

_AddMarkModel:

@model AutoStore.Domain.Core.CarModel

<div id="AddMarkModel" class="modal fade">
    <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">Добавление новой марки/модели</h4>
            </div>
            @using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "AddMarkSuccess", OnFailure = "AddMarkError" }))
            {
                <div class="modal-body">
                    @Html.Partial("_MarkModel")
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button>
                    <button id="btnConfirm" type="submit" class="btn btn-success">Добавить</button>
                </div>
            }
        </div>
    </div>
</div>

_MarkModel:

@model AutoStore.Domain.Core.CarModel

<div class="container">
    <div class="row">
        <div class="col">
            @Html.LabelFor(i => i.Mark.MarkName, "Марка")
        </div>
        <div class="col-sm-3">
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.RadioButton("Mark", "New", true)
                        <span>Новая</span>
                        @Html.EditorFor(i => i.Mark.MarkName, new { htmlAttributes = new { @id = "newMark", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Mark.MarkName, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.ModelName, "Модель")
                        @Html.EditorFor(i => i.ModelName, new { htmlAttributes = new { @id = "txtPass", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.ModelName, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-3">
            <div class="row">
                <div class="col">
                    @Html.RadioButton("Mark", "Existing")
                    <span>Существующая</span>
                    @Html.DropDownListFor(i => i.Mark.Id, ViewBag.marks as SelectList, new { @id = "exMark", @class = "form-control", @disabled = "disabled" })
                    @Html.ValidationMessageFor(i => i.Mark.MarkName, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
    </div>
</div>

从他们可以看出我正在使用 Html.AjaxBegin。

这导致了行动:

[HttpPost]
public JsonResult _AddMarkModel(CarModel model)
{
    if (model == null)
        throw new Exception("Модель не найдена");

    if (ModelState.IsValid)
    {
        unitOfWOrk.CarModels.Create(model);
        unitOfWOrk.Save();

        return Json(new { result = true });
    }
    else
        throw new Exception("Не все обязательные поля заполнены");
}

但是当我填写动作中的字段时,只有汽车型号的数据到达,而汽车品牌的数据没有到达:

在此处输入图像描述

虽然我有另一个使用 Car 类的表单,但 ajax.beginform 以相同的方式将数据传递给控制器​​。在外键的帮助下,所有其他模型的所有数据都被提取出来。这是汽车类:

public class Car
{
    public int Id { get; set; }
    [Required]
    [Display(Name = "Цена")]
    public int Price { get; set; }
    [Required]
    [Display(Name = "Количество на складе")]
    public int Count { get; set; }

    public int? MarkId { get; set; }
    public virtual Mark Mark { get; set; }

    public int CarModelId { get; set; }
    public virtual CarModel CarModel { get; set; }

    public int? EquipmentId { get; set; }
    public virtual Equipment Equipment { get; set; }

    public virtual ICollection<Order> Orders { get; set; }

    public Car()
    {
        Orders = new List<Order>();
    }
}

我怎么不明白有什么区别?请告诉我是否有人看到问题所在。也许问题出在数据库的体系结构中,在 car 的情况下实体以某种方式猜测将哪些数据放在哪里,但在 carmodel 的情况下却没有,但我无法理解到底是什么问题。

在此处输入图像描述

更新:

这是我描述的问题的工作代码示例。

楷模:

public class Car
    {
        public int Id { get; set; }
        [Required]
        [Display(Name = "Цена")]
        public int Price { get; set; }
        [Required]
        [Display(Name = "Количество на складе")]
        public int Count { get; set; }

        public int? MarkId { get; set; }
        public virtual Mark Mark { get; set; }

        public int CarModelId { get; set; }
        public virtual CarModel CarModel { get; set; }

        public int? EquipmentId { get; set; }
        public virtual Equipment Equipment { get; set; }

        public virtual ICollection<Order> Orders { get; set; }

        public Car()
        {
            Orders = new List<Order>();
        }
    }

public class Mark
    {
        public int Id { get; set; }
        [Required]
        [Display(Name = "Марка")]
        public string MarkName { get; set; }

        public virtual ICollection<CarModel> CarModels { get; set; }
        public virtual ICollection<Car> Cars { get; set; }

        public Mark()
        {
            CarModels = new List<CarModel>();
            Cars = new List<Car>();
        }
    }

public class CarModel
    {
        public int Id { get; set; }
        [Required]
        [Display(Name = "Модель")]
        public string ModelName { get; set; }

        public int MarkId { get; set; }
        public virtual Mark Mark { get; set; }

        public virtual ICollection<Equipment> Equipments { get; set; }
        public virtual ICollection<Car> Cars { get; set; }

        public CarModel()
        {
            Equipments = new List<Equipment>();
            Cars = new List<Car>();
        }
    }

public class Equipment
    {
        public int Id { get; set; }
        //Двигателя
        [Required]
        [Display(Name = "Двигатель")]
        public int Engine { get; set; }
        //Количество лошадиных сил
        [Required]
        [Display(Name = "Мощность")]
        public int Power { get; set; }
        //Год выпуска
        [Required]
        [Display(Name = "Год выпуска")]
        public int ReleaseYear { get; set; }
        //Тип привода
        [Required]
        [Display(Name = "Тип привода")]
        public string DriveType { get; set; }
        //КПП
        [Required]
        [Display(Name = "КПП")]
        public string Transmission { get; set; }
        //Кузов
        [Required]
        [Display(Name = "Кузов")]
        public string Body { get; set; }
        //Максимальная скорость
        [Required]
        [Display(Name = "Максимальная скорость")]
        public int MaxSpeed { get; set; }
        //Вес
        [Required]
        [Display(Name = "Вес")]
        public int Weight { get; set; }
        //Бак
        [Required]
        [Display(Name = "Бак")]
        public int MaxFuelVolume { get; set; }
        //Цвет автомобиля
        [Required]
        [Display(Name = "Цвет")]
        public string Color { get; set; }
        //Изорбражение автомобиля
        [Required]
        [Display(Name = "Изображение автомобиля")]
        public string Picture { get; set; }

        public int CarModelId { get; set; }
        public virtual CarModel CarModel { get; set; }

        public virtual ICollection<Car> Cars { get; set; }

        public Equipment()
        {
            Cars = new List<Car>();
        }
    }

在表格上,我添加了一辆新车,它具有其他车型的所有特征。我的表单,就像前面的例子一样,是由一个局部视图组成的。如果重要的话,我的局部视图窗口是模态的,并用 jquery 调用。他们来了:

_AddAuto:

@model AutoStore.Domain.Core.Car

<div id="AddAuto" class="modal fade">
    <div class="modal-dialog modal-lg" 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">Добавление нового автомобиля</h4>
            </div>
            @using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "AddCarSuccess", OnFailure = "AddCarError" }))
            {
                <div class="modal-body">
                    @Html.Partial("_CarAttributes")
                </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button>
                <button id="btnConfirm" type="submit" class="btn btn-success">Добавить</button>
            </div>
            }
        </div>
    </div>
</div>

_汽车属性:

@model AutoStore.Domain.Core.Car

<div class="container">
    <div class="row">
        <div class="col-sm-4">
            <div class="row">
                <div class="col">
                    @Html.Label("Автомобиль:")
                </div>
            </div>
            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Price, "Цена")
                        @Html.EditorFor(i => i.Price, new { htmlAttributes = new { @id = "txtPrice", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Price, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Count, "Количество на складе")
                        @Html.EditorFor(i => i.Count, new { htmlAttributes = new { @id = "txtCount", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Count, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Mark.MarkName, "Марка")
                        @Html.EditorFor(i => i.Mark.MarkName, new { htmlAttributes = new { @id = "txtMarkName", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Mark.MarkName, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.CarModel.ModelName, "Модель")
                        @Html.EditorFor(i => i.CarModel.ModelName, new { htmlAttributes = new { @id = "txtModelName", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.CarModel.ModelName, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <br />
                        @Html.LabelFor(i => i.Equipment.Picture, "Изображение Автомобиля", new { @style = "padding-right: 50px" })
                        @Html.EditorFor(i => i.Equipment.Picture, new { htmlAttributes = new { @class = "form-control", @type = "hidden", @id = "image" } })
                        <br />
                        @Html.ValidationMessageFor(i => i.Equipment.Picture, "", new { @id = "pictureError", @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        <input id="fileLoader" type="file" accept="image/*" />
                        <img id="autoPicture" class="img-responsive" />
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-6 col-sm-offset-1">
            <div class="row">
                <div class="col">
                    @Html.Label("Комплектация:")
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.Engine, "Двигатель")
                        @Html.EditorFor(i => i.Equipment.Engine, new { htmlAttributes = new { @id = "txtEngine", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.Engine, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.Power, "Мощность")
                        @Html.EditorFor(i => i.Equipment.Power, new { htmlAttributes = new { @id = "txtPower", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.Power, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.ReleaseYear, "Год выпуска")
                        @Html.EditorFor(i => i.Equipment.ReleaseYear, new { htmlAttributes = new { @id = "txtYear", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.ReleaseYear, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.DriveType, "Тип привода")
                        @Html.EditorFor(i => i.Equipment.DriveType, new { htmlAttributes = new { @id = "txtDriveType", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.DriveType, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.Transmission, "КПП")
                        @Html.EditorFor(i => i.Equipment.Transmission, new { htmlAttributes = new { @id = "txtTransmission", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.Transmission, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.Body, "Кузов")
                        @Html.EditorFor(i => i.Equipment.Body, new { htmlAttributes = new { @id = "txtBody", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.Body, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.MaxSpeed, "Максимальная скорость")
                        @Html.EditorFor(i => i.Equipment.MaxSpeed, new { htmlAttributes = new { @id = "txtMaxSpeed", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.MaxSpeed, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.Weight, "Вес")
                        @Html.EditorFor(i => i.Equipment.Weight, new { htmlAttributes = new { @id = "txtWeight", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.Weight, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.MaxFuelVolume, "Бак")
                        @Html.EditorFor(i => i.Equipment.MaxFuelVolume, new { htmlAttributes = new { @id = "txtFuel", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.MaxFuelVolume, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col">
                    <div class="form-group">
                        @Html.LabelFor(i => i.Equipment.Color, "Цвет")
                        @Html.EditorFor(i => i.Equipment.Color, new { htmlAttributes = new { @id = "txtColor", @class = "form-control" } })
                        @Html.ValidationMessageFor(i => i.Equipment.Color, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

请注意,但是在 partialview _CarAttributes 上,为了让我通过 Car 模型收集模型中的所有数据,我在 EditorFor 中爬到其他模型中,例如@Html.EditorFor(i => i.Equipment.Weight

这是我的控制器:

[HttpPost]
        public ActionResult _AddAuto(Car car)
        {
            if (car == null)
                throw new Exception("Автомобиль не найден");

            if (ModelState.IsValid)
            {
                unitOfWOrk.Cars.Create(car);
                unitOfWOrk.Save();

                return PartialView("_Car", car);
            }
            else
                throw new Exception("Не все обязательные поля заполнены");
        }

在此处输入图像描述

注意截图,所有数据不仅为 Car 模型填写,还为所有其他人填写,与我之前作为示例给出的 Weight 相同。如果您查看视图,您将看到一切。

这就是控制器中飞到我的地方:

在此处输入图像描述

Обратите внимание что хоть я и использую на вход модель Car но прилетают и все остальные модели. На последнем скриншоте я привёл пример только что помимо модели Car мне в контроллер пришла ещё и модель Equipment но там ещё пришли 2 модели, Mark и CarModel. Вот пример того что это работает.

Скрин:

在此处输入图像描述

javascript
  • 2 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-24 15:39:21 +0000 UTC

将base64字符串从服务器发送到客户端

  • 2

有一个任务。该页面有input type file. 用户向其添加图像。有了FileReader它,它被转换为 base64 并插入到img src. 页面上显示图像。结果,我将它传输到服务器并保存到数据库中。并且以后在编辑记录时,这个base64字符串会被传输到客户端,必须再次插入,img src这样用户才能看到编辑后的记录有什么图片。为了快速测试,我仍然有 1 个控制器,base64 字符串传递到该控制器并立即返回。有2张测试图片,更大和更小。两者都在访问ajax请求中发送到客户端,但是尝试插入时较大的那个会src崩溃并出现错误,而较小的那个被插入,但几乎整个cortina都模糊了。

JS:

//Добавление нового автомобиля
    $('#modalWindow').on('click', '#btnConfirm', function () {

        $.ajax({
            type: "POST",
            url: "/Home/_AddNewCar",
            data: $('form').serialize() + "&base64img=" + $('#autoPicture').attr('src'),
            success: function (data) {
                $('#autoPicture').attr('src', data);
            },
            error: function (error) {
                alert(error.responseText);
            }
        });
    });

    //Изменение содержимого загружаемого файла
    $('#modalWindow').on('change', '#fileLoader', function () {
        ReadImageUrl(this);
    });

    function ReadImageUrl(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.readAsDataURL(input.files[0]);

            reader.onload = function (e) {
                $('#autoPicture').attr('src', e.target.result);
            }
        }
        else {
            $('#autoPicture').attr('src', '');
        }
    }

控制器:

[HttpPost]
        public String _AddNewCar(Car car, string base64img)
        {
            return base64img;
        }

初始图像:

一)在此处输入图像描述

2)在此处输入图像描述

因此,对于第一个较大的,当尝试插入 src 时,会出现这样的错误:

在此处输入图像描述

而且根据第二张图,没有报错,但是将base64插入src后,结果是这样的:

在此处输入图像描述

请告诉我,可能是什么问题?毕竟,我什至不对字符串做任何事情,我立即将其发送回去。

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-16 21:27:41 +0000 UTC

排序模型时出现类型转换错误

  • 0

在 asp.net 上有一个应用程序。我决定为任何涉及它的模型编写一个接口和一个从它继承的排序类。一切通常都会得到一个排序的模型,但是当我试图在视图中吐出它时,问题就开始了。界面:

public interface IModelSort<T> where T : class
{
    IEnumerable<T> GetModelSort(IEnumerable<T> model, Func<T, dynamic> predSort, string typeSort);
}

继承自该接口的类:

public class ModelSort<T> : IModelSort<T> where T : class
{
    public IEnumerable<T> GetModelSort(IEnumerable<T> model, Func<T, dynamic> predSort, string typeSort = "Asc")
    {
        if (typeSort == "Asc")
            return model.OrderBy(predSort);
        else
            return model.OrderByDescending(predSort);
    }
}

接下来,我有一个名为 UnitOfBusiness 的类,它创建所有业务逻辑类的实例,包括这个:

public class UnitOfBusiness
{
    private ModelSort<dynamic> modelSorting;

    public ModelSort<dynamic> ModelSorting
    {
        get
        {
            if (modelSorting == null)
                modelSorting = new ModelSort<dynamic>();
            return modelSorting;
        }
    }
}

控制器:

public ActionResult Index(string sort, int page = 1)
{
    IEnumerable<Car> cars = unitOfWOrk.Cars.GetAll();
    var result = unitOfBusiness.ModelSorting.GetModelSort(cars, i => i.Price).ToList();
    return View(result);
}

最后查看:

@model PagedList.IPagedList<AutoStore.Domain.Core.Car>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

<h1>Каталог автомобилей</h1>

<style>
    html,
    body {
        height: 100%;
    }

    body {
        display: -ms-flexbox;
        display: flex;
        -ms-flex-align: center;
        padding-top: 40px;
        padding-bottom: 40px;
    }
</style>

<table class="table table-bordered">
    <thead>
        <tr>
            <th>
                @Html.ActionLink("Марка", "Index")
            </th>
            <th>Модель</th>
            <th>
                @Html.ActionLink("Цена", "Index")
            </th>
            <th>Количество на складе</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in ViewBag.Cars as List<AutoStore.Domain.Core.Car>)
        {
            <tr>
                <td>@Html.DisplayFor(i => item.Mark.MarkName)</td>
                <td>@Html.DisplayFor(i => item.CarModel.ModelName)</td>
                <td>@Html.DisplayFor(i => item.Price)</td>
                <td>@Html.DisplayFor(i => item.Count)</td>
            </tr>
        }
    </tbody>
</table>

结果,视图出现错误:

传入字典的模型项的类型为“System.Collections.Generic.List 1[System.Object]', but this dictionary requires a model item of type 'PagedList.IPagedList1[AutoStore.Domain.Core.Car]”。

我尝试使用

 result.ToPagedList(page, 8)

结果相同。我试图从错误中获益,并将其放在页面列表中的视图上,而不是模型、对象上,然后另一个错误发生了。

对象引用不指向对象的实例。

如果您通过 ViewBag 传递已排序的机器列表,则会发生同样的错误。请告诉我可以做什么?我已经伤透了脑筋。

c#
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-12 23:31:06 +0000 UTC

尚未授权打开网站的同一页面

  • 1

asp.net mvc上有一个应用程序。创建应用程序时,我选择了身份验证类型 No Authentication。我想使用表单身份验证。我需要应用程序始终从同一页面开始。即使我从 Visual Studio 打开另一个视图进行编辑并启动项目,它仍然重定向到默认页面。我发现需要在 web 配置中编写什么,以便应用程序像这样工作。

<authentication mode="Forms">
    <forms loginUrl="~/Authorization/Index" timeout="2880"/>
</authentication>

在网络配置中写了这个。例如,我有 2 页注册和授权。我选择在同一控制器的另一种方法负责的 Visual Studio 视图中进行编辑,我/Authorization/Registration启动应用程序并为我启动注册页面。也就是说,重定向到授权页面不起作用。请告诉我我做错了什么?我怎样才能使重定向工作?

c#
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-11 15:40:09 +0000 UTC

使用 abort() 取消 ajax 请求

  • 0

我在 Internet 上找到了如何在必要时取消执行 ajax 请求。现在,如果表单字段为空并且没有传递任何内容,我需要取消它。这是我的代码:

$('#btnConfirm').on('click', function () {
        if ($('#pass').css('display') == 'none') {
            AjaxPassRecovery("/Authorization/FindUserAccount", Success)
        }
    });

function AjaxPassRecovery(url, callback) {
        var xhr = $.ajax({
            beforeSend: function () {
                var mail = $('#txtMail').val();
                if (mail === '')
                    xhr.abort();
            },
            type: "POST",
            url: url,
            data: {
                "Email": $('#txtMail').val()
            },
            success: function (result) {
                callback(result);
            },
            error: function (xhr) {
                swal({
                    title: xhr.responseText,
                    type: "warning"
                });
            }
        });
    }

function Success(result) {
        if (result > 0) {
            $('#txtMail').attr('readonly', 'readonly');
            $('#pass').slideDown();
        }
    }

我将带有 ajax 请求的函数的执行绑定到按钮,并使用回调在其中调用成功函数。这就是我在示例中的 xhr 变量中找到 ajax 请求的方式。并且在发送ajax请求之前,我检查该字段是否为空,然后取消请求。但是会抛出一个错误。 在此处输入图像描述

我认为这是范围问题并在此页面上全局声明了 xhr 变量,但错误是相同的。怎么了?我究竟做错了什么?我在互联网上看到的例子看起来差不多。

javascript
  • 2 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-02 21:14:15 +0000 UTC

从 bootstrap3 移动到 4 时,元素边缘的舍入丢失

  • 1

对于注册页面,我使用了很棒的字体图标。我将它们连接到输入字段。然后我在边缘对结果元素进行四舍五入。使用引导版本 3.3.7 一切正常。编码:

<div class="form-group">
                <label for="name" class="cols-sm-2 control-label">Your Name</label>
                <div class="cols-sm-10">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
                        <input type="text" class="form-control" name="name" id="name" placeholder="Enter your Name" />
                    </div>
                </div>
            </div>

CSS:

.form-control {
        border-radius: 30px;
    }

    .input-group-addon {
        border-radius: 30px;
    }

结果:

在此处输入图像描述

使用新版本的 bootstrap 4.1.3,这不再可能。这是我的代码:

<div class="form-group">
            @Html.LabelFor(i => i.CSurname, "Фамилия")
            <div class="cols-sm-10">
                <div class="input-group">
                    <span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
                    @Html.EditorFor(i => i.CSurname, new { htmlAttributes = new { @class = "form-control", @placeholder = "Введите фамилию" } })
                </div>
            </div>
        </div>

input-group-addon在这里你需要使用它,input-group-text否则一切都是一样的。CSS是一样的:

.input-group-text {
        border-radius: 30px
    }

    .form-control {
        border-radius: 30px
    }

结果是不同的:

在此处输入图像描述

请告诉我我做错了什么?我想像第一次一样取得成果。

这是代码的最后一个版本:

<div class="container">
    <div class="form-signin">
        <div class="form-group">
            @Html.LabelFor(i => i.CSurname, "Фамилия")
            <div class="cols-sm-10">
                <div class="input-group">
                    <span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
                    @Html.EditorFor(i => i.CSurname, new { htmlAttributes = new { @id = "txtSurname", @class = "form-control", @placeholder = "Введите фамилию" } })
                    @Html.ValidationMessageFor(i => i.CSurname, null, new { @class = "text-danger" })
                </div>
            </div>
        </div>

CSS:

.input-group-text {
        border-top-left-radius: 30px;
        border-bottom-left-radius: 30px;
    }

    .form-control {
        border-radius: 30px;
    }

截屏:

在此处输入图像描述

生成的标记示例:

<div class="container">
    <div class="form-signin">
        <div class="form-group">
            <label for="CSurname">Фамилия</label>
            <div class="cols-sm-10">
                <div class="input-group">
                    <span class="input-group-text"><i class="fa fa-id-badge" aria-hidden="true"></i></span>
                    <input class="form-control text-box single-line" data-val="true" data-val-required="Требуется поле CSurname." id="txtSurname" name="CSurname" placeholder="Введите фамилию" type="text" value="" />
                    <span class="field-validation-valid text-danger" data-valmsg-for="CSurname" data-valmsg-replace="true" id="mess"></span>
                </div>
            </div>
        </div>

在此处输入图像描述

c#
  • 2 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-01-01 21:51:27 +0000 UTC

在 ASP.NET MVC 应用程序中使用接口

  • 1

我正在研究使用 asp.net mvc 作为示例的应用程序架构。我在网站 metanit 上学习。在那里,在关于洋葱架构的示例中,在控制器中创建了一个存储库接口的实例。这是元尼特代码:

IBookRepository repo;
IOrder order;
public HomeController(IBookRepository r, IOrder o)
{
    repo = r;
    order = o;
}
public ActionResult Index()
{
    var books = repo.GetBookList();
    return View();
}

但是同样成功,您可以创建存储库本身的实例(类的实例),并且会得到相同的结果:

BookRepository repo;
Order order;
public HomeController(BookRepository r, Order o)
{
    repo = r;
    order = o;
}
public ActionResult Index()
{
    var books = repo.GetBookList();
    return View();
}

那有什么区别呢?创建类的实例或接口的实例。你能解释一下吗?

c#
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-12-24 15:55:42 +0000 UTC

使用其他按钮类型时未发送请求

  • 1

请告诉我为什么如果您使用Ajax.BeginForm,那么您需要使用提交类型的按钮来提交表单,如果您使用 jquery $.ajax,那么您只需按钮并且表单仍然可以。有什么区别?帮助代码:

<div>
    @using (Ajax.BeginForm("BookSearch", new AjaxOptions
    {
        UpdateTargetId = "results"
    }))
    {
        <input type="text" name="name" />
        <input type="submit" value="Поиск" />
    }
    <div id="results"></div>
</div>

带有 jquery 的代码:

<div>
    <input id="txt" type="text" name="name" />
    <input id="btn" type="button" value="Поиск" />
    <div id="results"></div>
</div>

@section scripts {
    <script type="text/javascript">
        $('#btn').on('click', function () {
            $.ajax({
                type: "POST",
                url: "/Home/BookSearch",
                data: { "name": $('#txt').val() },
                success: function (data) {
                    $('#results').html(data);
                },
                error: function (xhr) {
                    alert(xhr.status + 'Ошибка');
                },

            });
        });
    </script>
}

这就是这两个选项的工作方式,但如果在第一种情况下我还键入输入按钮,那么请求将不起作用。为什么?

c#
  • 2 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-12-20 13:52:57 +0000 UTC

使用 ajax 请求调用模式

  • 0

我正在尝试使用 ajax 请求调用模式窗口,但出现了问题。该窗口仅通过按 2 次按钮调用,之后它不会关闭,您也无能为力。这是我的代码:调用模态的主视图的代码:

@{
    ViewBag.Title = "Index";
}

@model IEnumerable<AjaxTest.Models.Book>

<h2>Каталог книг</h2>

<input id="modShow" type="submit" value="Добавить" data-toggle="modal" data-target="#mod" />

<div id="result"></div>

<body>
    <div>
        <table id="tab" class="table" table-bordered>
            <thead>
                <tr>
                    <th>Название</th>
                    <th>Автор</th>
                    <th>Цена</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(i => item.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Author)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Price)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</body>

<h2>Список пользователей</h2>

<body>
    <div>
        <table class="table" table-bordered>
            <thead>
                <tr>
                    <th>Имя</th>
                    <th>Фамилия</th>
                    <th>Возраст</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in ViewBag.Users as List<AjaxTest.Models.User>)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(i => item.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Surname)
                        </td>
                        <td>
                            @Html.DisplayFor(i => item.Age)
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</body>

@section scripts{
    <script type="text/javascript">
        $('#btnAdd').on('click', function () {
            $.ajax({
                type: "POST",
                url: "/Home/Create",
                data: {
                    "Name": $('#txtName').val(),
                    "Author": $('#txtAuthor').val(),
                    "Price": $('#txtPrice').val()
                },
                success: function (data) {
                    $('#tab tbody').append(data);
                }
            });
        });

        $('#result').on('hidden.bs.modal', function () {
            $('#result').remove();
        });

        $('#modShow').on('click', function () {
            $.ajax({
                type: "POST",
                url: "/Home/ModalCreate",
                success: function (data) {
                    $('#result').html(data);
                }
            });
        });
    </script>
}

控制器代码:

[HttpPost]
        public ActionResult ModalCreate()
        {
            return PartialView();
        }

带模态的部分视图代码:

<div id="mod" class="modal fade" >
    <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">Новая книга</h4>
            </div>
            <div class="modal-body">
                <table>
                    <tr>
                        <td><p>Название</p></td>
                        <td><input type="text" id="txtName" /></td>
                    </tr>
                    <tr>
                        <td><p>Автор</p></td>
                        <td><input type="text" id="txtAuthor" /></td>
                    </tr>
                    <tr>
                        <td><p>Цена</p></td>
                        <td><input type="text" id="txtPrice" /></td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button>
                <button id="btnAdd" type="submit" data-dismiss="modal" class="btn btn-primary">Добавить</button>
            </div>
        </div>
    </div>
</div>

请告诉我我做错了什么?

我添加了一个按钮来显示模式并更改了用于执行此操作的按钮,这是他们的代码:

<input id="modRender" type="submit" value="Добавить" />
<button style="display: none" id="modShow"  data-toggle="modal" data-target="#mod"></button>

现在,一个按钮在页面上显示部分视图,第二个按钮调用模式窗口。当然,修改后的 ajax 请求代码调用所有这些以及删除对象的方法。

$('#result').on('hidden.bs.modal', function () {
            $('#result*').remove();
        });

        $('#modRender').on('click', function () {
            $.ajax({
                type: "POST",
                url: "/Home/ModalCreate",
                success: function (data) {
                    $('#result').html(data);
                    $('#modShow').click();
                }
            });
        });

事实证明,当模态关闭事件触发时,我删除了 div 中带有 id 结果的所有内容。然后另一个窗口没有被调用,我做错了什么请告诉我?

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-12-19 12:45:40 +0000 UTC

在 asp.net mvc 项目中使用 json 的 Ajax 请求

  • 1

我正在学习 JavaScript。得到ajax请求。我有一个用 jquery 编写的查询。查看代码:

@{
    ViewBag.Title = "Index";
}

<div>
    <input type="text" name="name" id="txt" />
    <input type="button" id="btn" class="edit" value="Отправить" />

    @section scripts {
        <script type="text/javascript">
            $('#btn').on('click', function () {

                var message = { "name": $('#txt').val() };

                $.ajax({
                    type: "POST",
                    url: "/Home/BookSearch",
                    data: JSON.stringify(message),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert('Успех');
                        $('#results').html(data);
                    },
                    error: function (xhr) {
                        alert(xhr.status + 'Ошибка');
                    }
                });
            });
        </script>
    }

    <div id="results"></div>

</div>

一开始我尝试不将字符串变量转换为json,而是直接以字符串的形式传递。一切都很好,请求完成返回成功。像现在在代码中一样尝试。请求被执行,它返回了想要的结果,但由于某种原因,它更进一步的错误函数,但同时我检查 xhr.status 或 c# 仍然有 enum HttpStatusCode 并且这个状态是 200,相当于好的。那么为什么然后去错误分支呢?但是如果我从这个请求中删除一行,dataType: "json",那么一切都会像没有 json 一样正常工作。我不明白为什么会这样。如果需要,这是我的控制器代码:

Context db = new Context();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult BookSearch(string name)
        {
            var allbooks = db.Books.Where(a => a.Author.Contains(name)).ToList();

            if (allbooks.Count <= 0)
            {
                return HttpNotFound();
            }

            return View(allbooks);
        }
javascript
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-12-18 20:14:26 +0000 UTC

使用第三方文件中的 javascript 函数

  • 0

我正在学习js,还不太了解。我有一个 mvc 项目。它使用 ajax 请求。并根据请求的结果,无论是成功还是错误,都会执行该函数。如果我直接在 ajax 函数请求本身中编写,一切正常。我尝试写入第三方文件,但一切都与我预期的有所不同。以下是带有函数的第三方文件的代码:

$(function successFunc (data) {
    alert('Успех');
    $('#results').html(data);
});

$(function errorFunc(xhr) {
    alert(xhr.status + 'Ошибка');
});

文件本身包含在布局中:

@Scripts.Render("~/scripts/Result.js")

这是带有ajax请求的视图代码:

@{
    ViewBag.Title = "Index";
}

<div>
    <input type="text" name="name" id="txt" />
    <input type="button" id="btn" class="edit" value="Отправить" />

    @section scripts {
        <script type="text/javascript">
            $('#btn').on('click', function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/BookSearch",
                    data: { "name": $('#txt').val() },
                    success: successFunc(data),
                    error: errorFunc(xhr)
                });
            });
        </script>
    }

    <div id="results"></div>

</div>

因此,这两个函数都会在应用程序启动时立即执行。以及如何使它们仅在 ajax 请求的结果上执行,因为它应该是?

视图内带有函数的代码:

@{
    ViewBag.Title = "Index";
}

<div>
    <input type="text" name="name" id="txt" />
    <button id="btn">Отправить</button>

    @using (Ajax.BeginForm("BookSearch", new AjaxOptions { UpdateTargetId = "results" }))
    {
        <input type="text" name="name" />
        <input type="submit" value="Поиск" />
    }

    @section scripts {
        <script type="text/javascript">
            $('#btn').on('click', function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/BookSearch",
                    data: { "name": $('#txt').val() },
                    success: function (data) {
                        alert('Успех');
                        $('#results').html(data);
                    },
                    error: function (xhr) {
                        alert(xhr.status + 'Ошибка');
                    },

                });
            });
        </script>
    }

    <div id="results"></div>

</div>
javascript
  • 1 个回答
  • 10 Views
Martin Hope
Андрей
Asked: 2020-12-14 19:59:04 +0000 UTC

使用 DataAnnotations 库

  • 1

请告诉我注解 [DataType(DataType.Password)] 是什么意思?例如,如果我在视图中使用 @Html.Password 助手或者只是在助手处写入 textbox new { @type = "password" },那么当我在此字段中输入字符时,字符将显示为密码的星号安全。但是我试图在模型中的属性上放置一个带有密码类型的注释。没有这样的事情发生。那么这个注解有什么用呢?

c#
  • 2 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5