小编Mar*_*rco的帖子

asp.net按钮事件没有触发

我有个问题.当我从代码后面添加一个事件处理程序到一个按钮时,事件永远不会被触发.但是当我在创建按钮标签时添加它时,它完美地工作,我从后面的代码创建按钮,然后将其添加到表中.

<form id="form1" runat="server">
    <div>                       
        <asp:Button ID="Button1" runat="server" Text="show table" OnClick="Button1_OnClick" />
        <table border="1">
            <thead>
                <tr>
                </tr>
            </thead>
            <tbody id="tbody" runat="server">

            </tbody>
        </table>
    </div>
</form>


protected void Button1_OnClick(object sender, EventArgs e)
{
  var row = new TableRow(); 
  var btnDownload = new Button { ID = "ID", Text = "Click Here" };
  btnDownload.Click += ClickEvent;
  var cell = new TableCell();
  cell.Controls.Add(btnDownload);
  row.Controls.Add(cell);
  tbody.Controls.Add(row);
}
protected void ClickEvent(object sender, EventArgs e)
{
  Debug.WriteLine(((Button)sender).Text);
}
Run Code Online (Sandbox Code Playgroud)

asp.net events code-behind buttonclick

3
推荐指数
2
解决办法
1万
查看次数

字符串替换不在asp.net中工作

string mystring="the are boys";

string[] tags = {"the"};

string[] replace ={"they"}

mystring.Replace(tags[0],replace[0]) // is not working

mystring.Replace("the","they") // is working 
Run Code Online (Sandbox Code Playgroud)

我认为两者都是一样的,但第一个声明不起作用.第二个是.请帮我解决问题.

c# replace

3
推荐指数
1
解决办法
533
查看次数

无法将类型'System.Linq.IQueryable <TMS.Models.CustomAsset>'隐式转换为'System.Collections.Generic.ICollection

我有以下模特课: -

public class CustomerCustomAssetJoin
{
    public CustomAsset CustomAsset  { get; set; }
    public ICollection<CustomAsset> CustomAssets { get; set; }

} 
Run Code Online (Sandbox Code Playgroud)

但是当我写下面的方法时: -

public CustomerCustomAssetJoin CustomerCustomAsset(string customerName)
{
    var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());
    CustomerCustomAssetJoin caj = new CustomerCustomAssetJoin
    {
         CustomAsset = new CustomAsset {CustomerName = customerName },
         CustomAssets = customerAssets
    };
    return caj;  
 }
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

错误20无法将类型'System.Linq.IQueryable'隐式转换为'System.Collections.Generic.ICollection'.存在显式转换(您是否错过了演员?)

那是什么导致了这个错误?要克服此错误,我只需添加.toList(),如下所示:

var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());
Run Code Online (Sandbox Code Playgroud)

那么为什么我必须将其转换为列表?

c# asp.net-mvc asp.net-mvc-4

3
推荐指数
1
解决办法
9760
查看次数

Newtonsoft JSON.NET 和 json 关键错误中的空格?

获取以下有效的 json:

{
   "universe": {
      "solar system": "sun"
   }
}
Run Code Online (Sandbox Code Playgroud)

这是简单的 C# 代码:

using Newtonsoft.Json;
JToken x = JToken.Parse("{\"universe\": {\"solar system\": \"sun\"}}");
string s = x.First.First.First.Path;
Run Code Online (Sandbox Code Playgroud)

在此刻s = "universe['solar system']"

然而我期待着"universe.['solar system']"(注意“宇宙”后面的“.”)。

如果 json 键没有空格(“solar_system”),我得到的"universe.solar_system"结果是正确的。

问题是:这是 json.net 中的错误还是我需要做其他事情来支持 json 键中的空格?

谢谢,

PT

c# json json.net

3
推荐指数
1
解决办法
2784
查看次数

linq查询并使用结果来设置属性

我有一个对象列表,我需要根据一个字段是否具有唯一值来设置一个字段。

考虑具有两个属性的票证类

public class Ticket
{
    public string TicketNumber { get; set; }

    public bool IsUnique { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我收到票证清单,并将其传递给函数:

 IList<Ticket>
Run Code Online (Sandbox Code Playgroud)

我想使用linq遍历此列表,如果给定的票证号码在该列表中是唯一的,请将bool IsUnique设置为true。

到目前为止,我有以下内容

public void UpdateTickets(IList<Ticket> Tickets)
    {
        foreach (var ticket in tickets)
        {
            // if ticketNumber occurs once
            // set isUnique to true, otherwise false
        }
    }
Run Code Online (Sandbox Code Playgroud)

c# linq

3
推荐指数
1
解决办法
69
查看次数

字节串到字节数组c#

在我的Web应用程序中,我连接到Web服务.在我的Web服务中,它有一个根据路径获取报告字节的方​​法:

public byte[] GetDocument(string path)
{
   byte[] bytes = System.IO.File.ReadAllBytes(path);
   return bytes;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我从我的Web应用程序发出请求时,Web服务给了我一个Json对象,类似于:

{
  "Report":"0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAA
   AAACAAAA3QAAAAAAAAAAEAAA3wAAAAEAAAD+ ... (continues)" 
}
Run Code Online (Sandbox Code Playgroud)

在我的Web应用程序中,我有一个获取Json对象的方法,将"report"放在一个字符串中.然后,Web应用程序有一个方法将字符串解析为字节数组,这不起作用,它抛出一个FormatException:

public byte[] DownloadReport(string id, string fileName)
{
    var fileAsString = _api.DownloadReport(id, fileName);
    byte[] report = fileAsString.Split()
                                .Select(t => byte.Parse(t, NumberStyles.AllowHexSpecifier))
                                .ToArray();
    return report;
}
Run Code Online (Sandbox Code Playgroud)

我也试过这样做:

public byte[] DownloadReport(string id, string fileName)
{
   var fileAsString = _api.DownloadReport(id, fileName);
   byte[] report = Encoding.ASCII.GetBytes(fileAsString);
   return report;
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个.doc文件,其中包含与Json对象完全相同的字符串.

我是从Web服务解析错误的方法,还是我想再次将其转换为字节数组?

c# byte json

2
推荐指数
1
解决办法
7844
查看次数

从 Viewbag.List 中查找项目

我的控制器代码如下

ViewBag.Districts = (from a in _dbContext.DISTRICTS 
                     select new ComboItem { 
                                            ID = a.DISTRICT_ID, 
                                            Name = a.DISTRICT_NAME 
                                          }
                     ).ToList();
Run Code Online (Sandbox Code Playgroud)

我的Razor View代码如下

@foreach (var dist in ViewBag.Districts)
{
    if (item.DISTRICT_ID == dist.ID)
    {
        @dist.Name
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以在 ViewBag.Districts 中找到类似ViewBag.Districts.where(m=>m.ID==item.DISTRICT_ID. 或 linq 表达式的项目,以便我可以避免循环。任何人帮助我都非常感激。

c# linq asp.net-mvc

2
推荐指数
1
解决办法
8632
查看次数

使用当前日期创建文件名

在我的C#Windows Forms应用程序中,我有日志数据。我将它们保存在一个文本文件中,但是我想用当前日期/时间的一些描述来命名该文件。但是在调试代码时,我得到了这个错误:

不支持给定路径的格式。

这是我的代码:

        string dateAndTime = " '' " + DateTime.Now.ToShortDateString() + "-" + DateTime.Now.ToShortTimeString() + " '' ";
        string sPath = @"C:/Desktop/Logs - "+ dateAndTime + ".txt";
        int type = 0;
        using (StreamWriter sw = File.CreateText(sPath))
        {
            int J = 0;
            for (int i = 0; i < logsList.Count; i++)
            {
                if (logsList[i + 3] == "IN")
                {
                    type = 3;
                }
                else if (logsList[i + 3] == "OUT")
                {
                    type = 4;
                }

                sw.WriteLine(logsList[i] + "          " …
Run Code Online (Sandbox Code Playgroud)

c# directory datetime

2
推荐指数
1
解决办法
4261
查看次数

相同视图中的c#2模型

我想在同一页面中获取2个视图.在我的HomeController中,我得到了我的数据库的信息.但是当我想在我的视图中显示信息时,我遇到了问题.

Homecontroler

 public ActionResult DetailEquipe()
    {
        List<EquipePersonnel> Viewep = new List<EquipePersonnel>();

        string path = HttpContext.Request.Url.AbsolutePath;
        //string id = path.Substring(path.LastIndexOf("/"));
        string id = System.IO.Path.GetFileName(path);
        ViewBag.ID = id;

        ViewBag.test = "testfail";
        List<Equipe> equipe = new List<Equipe>();
        List<Personnel> personnel = new List<Personnel>();
        try
        {
            using (var connection = new QC.SqlConnection(
         "Server = connection...."
         ))
            {
                connection.Open();
                Console.WriteLine("Connected successfully.");
                using (var command = new QC.SqlCommand())
                {
                    command.Connection = connection;
                    command.CommandType = DT.CommandType.Text;
                    command.CommandText = @"Select * from Equipe where Id='" + id + "'"; …
Run Code Online (Sandbox Code Playgroud)

c# visual-studio

2
推荐指数
1
解决办法
109
查看次数

如何模拟使用规则集的 AbstractValidator?

我有一个抽象验证器,具有以下结构:

public abstract class RiskAssessmentServiceCreateRequestValidator<T>
    : AbstractValidator<T> where T
        : IRiskAssessmentServiceCreateRequest
{
    public RiskAssessmentServiceCreateRequestValidator(ApplicationContext context)
    {
        RuleSet("modelBinding", () =>
        {
            RuleFor(x => x.ServiceProviderId).NotNull().GreaterThan(0);
        });

        RuleSet("handler", () =>
        {
            //....
        });

    }
}
Run Code Online (Sandbox Code Playgroud)

在我的请求处理程序中,我像这样调用此类的派生实例:

var validationResult = _validator.Validate(request, ruleSet: "handler");
Run Code Online (Sandbox Code Playgroud)

如何在单元测试中模拟对 Validate 的特定调用?如果我不使用规则集,我的设置将如下所示:

_validator.Setup(x => x.Validate(It.IsAny<CreateRequest>()))
          .Returns(validationResult);
Run Code Online (Sandbox Code Playgroud)

不允许以下调用,因为表达式树中不允许使用可选参数:

_validator.Setup(x => x.Validate(
                It.IsAny<CreateRequest>(), 
                ruleSet: It.IsAny<string>()))
          .Returns(validationResult);
Run Code Online (Sandbox Code Playgroud)

理论上我可以这样设置:

_validator.Setup(x => x.Validate(
                It.IsAny<CreateRequest>(), 
                (IValidatorSelector)null,
                It.IsAny<string>()))
           .Returns(validationResult);
Run Code Online (Sandbox Code Playgroud)

但这会导致:

System.NotSupportedException : Unsupported expression: x => x.Validate<CreateRequest>(It.IsAny<CreateRequest>(), null, It.IsAny<string>())
    Extension methods (here: DefaultValidatorExtensions.Validate) may not be used …
Run Code Online (Sandbox Code Playgroud)

c# moq fluentvalidation

2
推荐指数
1
解决办法
1073
查看次数