这是我到目前为止所做的:
@Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = "UpdateProduct(this);" })
<script language="JavaScript">
$('#id').on('change', function () {
var data = { prodID: 5, catID: 8 }; // < added test values
$.post('GiftList/UpdateProduct', data, function (responseData) {
//callback function
});
});
</script>
这是我更新的操作方法:
[HttpPost]
public ActionResult UpdateProduct(int prodID, int catID)
{
........
product.Category= catID;
_productService.UpdateProduct(product);
...
我只是不知道如何“连接”这一切。
原始问题:
我有一个DropDown,当一个项目被选中时,会运行一些代码 并更新数据库中的Product表。
此下拉列表包含类别表(ID和名称)中的项目:
@Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = "UpdateProductsDB(this);" })
我需要传入所选类别的'id'字段。
我还需要从Product表中传递Product Id以进行更新。
我可以在View by:
中访问Product Id('id') @foreach (var item in Model.Products)
{ ....
item.Id
我添加的隐藏字段:
<input id="item_Id" name="item.Id" type="hidden" value="43" />
MVC甚至可以实现吗?从我的搜索,似乎jQuery会做到这一点。 请提供尽可能多的详细信息,因为我根本不了解jQuery。
<tr><span >Panasonic HDC-SDT750K</span>
<input id="item_Id" name="item.Id" type="hidden" value="41" />
</tr>
<tr>
<td width="125px" height="20px" align="right">Model: </td>
<td width="325px" align="left">
<span style="display:inline-block;width:325px;"></span>
</td>
................
<select id="id" name="id" onchange="UpdateProductsDB(this);">
<option value="5">Accessories</option>
<option selected="selected" value="1">Desktops</option>
<option value="8">Camera, photo</option>
<option value="9">Cell phones</option>
<option value="12">Jewelry</option> . . .
</select>
</td>
<td ><a href="/DBMJ33/GiftList/Edit/id41">Edit</a></td>
<td ><a href="/DBMJ33/GiftList/Delete/id41">Delete</a>
答案 0 :(得分:6)
这可以让你走上正轨。
//your javascript
$('#myDropdown').on('change', function(){
var data = {someData : someDataValue, someMoreData : someMoreDatavalue};
$.post('myControllerName/UpdateProduct', data, function(responseData){
//callback function
});
});
//in your controller
[HttpPost]
public ActionResult UpdateProduct(int someData, string someMoreData)
{
//do something with your data
}
答案 1 :(得分:3)
试试这个
@Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = string.Format("UpdateProductsDB(this, {0})", item.id) })
您的UpdateProductsDB函数现在也将接受id。
function UpdateProductsDB(categorySelected, productId) {
...
}
同样取决于你的id的类型,如果它是一个整数而不是你可以使用:
string.Format("UpdateProductsDB(this, {0})", item.id)
但如果它是GUID或字符串,则必须放置单引号:
string.Format("UpdateProductsDB(this, '{0}')", item.id)
答案 2 :(得分:3)
原来我根本不需要jQuery或AJAX,只需要这3行。 当在下拉列表中选择一个项目时,这个&#34;回发&#34;或立即运行:
@using (Html.BeginForm("UpdateProduct", "GiftList"))
{
@Html.Hidden("prodID", item.Id)
@Html.DropDownList("catID", (SelectList)ViewBag.Values, new { onchange = "this.form.submit();" })
}