gpt4 book ai didi

c# - 通过查询字符串传递 Int 类型值

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:20 25 4
gpt4 key购买 nike

我能够成功传递字符串值,但无法通过查询字符串传递整数值。

如果我只传递字符串对象,URL 看起来像

www.website.com/mypage?ProductName=TestName&MahName=TestName(正确)

但是,如果我将 Id (int) 与查询字符串一起传递,则 URL 如下所示

www.website.com/mypage/1?ProductName=TestName&MahName=TestName(不正确)

但是,我希望它是

www.website.com/mypage?Id=1&ProductName=TestName&MahName=TestName

模型

using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;

namespace SecureMedi.Models
{
public class CustomProductData
{
[Required]
public int Id { get; set; }

[StringLength(200)]
public string ProductName { get; set; }

[StringLength(100)]
public string MahName { get; set; }

public static CustomProductData FromSqlReader(SqlDataReader rdr)
{
return new CustomProductData
{
Id = (int)rdr["id"],
ProductName = rdr["product_name"].ToString(),
MahName = rdr["mah_name"].ToString()
};
}
}
}

Controller

[HttpGet]
public ActionResult CustomProductData(int Id, string ProductName, string MahName) {
var model = new CustomProductData() {
Id = Id,
ProductName = ProductName,
MahName = MahName
};

return View(model);
}

[HttpPost]
public ActionResult CustomProductData(CustomProductData cp) {
try {
using(ISecureMediDatabase db = new SecureMediDatabase(this)) {
CustomProductDataDAL cpd = new CustomProductDataDAL(db);
cpd.Edit(cp);
return RedirectToAction("LoadCustomProductData");
}
} catch (Exception ex) {
ModelState.AddModelError("", ex.Message);
return View(cp);
}
}

DAL

public void Edit(CustomProductData cp) {
try {
string sql = "UPDATE table_name SET product_name = @ProductName, mah_name = @MahName WHERE id = @Id";

if (cp.HasDetails()) {
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
cmd.Parameters.Add(new SqlParameter("@Id", cp.Id));
cmd.Parameters.Add(new SqlParameter("@ProductName", cp.ProductName));
cmd.Parameters.Add(new SqlParameter("@MahName", cp.MahName));
PrepareCommand(cmd);
cmd.ExecuteNonQuery();
}
}
} catch {
closeConnection();
throw;
}
}

cshtml

用于将查询字符串值传递到编辑页面的 anchor 链接(从 QueryString 获取值)

<td class="text-secondary">@Html.ActionLink("Edit", "CustomProductData", "Home", new { Id = @item.Id, ProductName = @item.ProductName, MahName = @item.MahName }, new { @class = "text-info" })</td>

最佳答案

显然,变量名Id在路由中被占用,因此将变量名Id更改为RecordId解决了问题。

关于c# - 通过查询字符串传递 Int 类型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com