I am able to successfully pass string values, but having trouble passing integer value via Query String.
If I only pass string objects the URL looks like
www.website.com/mypage?ProductName=TestName&MahName=TestName (Correct)
However, if I pass Id (int) along with the query string the URL looks like
www.website.com/mypage/1?ProductName=TestName&MahName=TestName (Incorrect)
However, I would like it to be
www.website.com/mypage?Id=1&ProductName=TestName&MahName=TestName
Model
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 link to pass the query string values to the edit page (which take the values from the 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>