我能够成功传递字符串值,但是无法通过查询字符串传递整数值。
如果我仅传递字符串对象,则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()
};
}
}
}
控制器
[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
锚定链接,用于将查询字符串值传递到编辑页面(该页面从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>
答案 0 :(得分:3)
显然,路由中使用了变量名Id
,因此将变量名Id
更改为RecordId
就解决了这个问题。