使用Ajax将参数从视图传递到控制器,但实际上,参数显示为空
我尝试通过首先获取变量中的值并将变量作为参数传递来传递数据
Ajax请求
$.ajax({
type: 'GET',
url: '/Product/Edit',
data: { Id: $(this).attr('dataid') }, //Id is fetching data but not getting passed to controller
dataType: "json",
contentType: "application/json; charset=utf-8"
});
操作:
public ActionResult Edit(int Id)
{
var Category = ServProd.GetProductForId(Id);
return PartialView(Category);
}
按钮:
<button class="ProdEdit" type="button" dataid="@Prod.Id">Edit</button>
答案 0 :(得分:0)
1)修改您的AJAX调用,使其看起来像这样:
insertImage()
2)创建一个C#模型:
const dataToSend = { Id: $(this).attr('dataid') };
$.ajax({
type: 'GET',
url: '/Product/Edit',
data: JSON.stringify(dataToSend),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(`Request passed!`);
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(`Request failed!`);
}
});
3)将操作方法更改为:
public class MyModel
{
public int Id { get; set; }
}
现在将进行适当的model binding并将您的public ActionResult Edit(MyModel RequestModel)
{
var Category = ServProd.GetProductForId(RequestModel.Id);
return PartialView(Category);
}
放入Id
属性中。