0
저는 MVC와 JavaScript를 처음 접했고, 일부 사람들에게는 분명한 대답이 될 수 있지만 (많은 예제를 본 후에) 지금 당분간 어려움을 겪고 있습니다!컨트롤러에 JSON 객체 전달하기
Index.cshtml보기를 통해 디버깅 할 때 newData 객체는 텍스트 상자로 채워지지 않습니다 (AddNewProduct.cshtml이라는 부분 뷰에 설정 됨). 부분보기는 Index.cshtml (이 잘 작동합니다) 내에 설정된 버튼을 클릭하여 표시됩니다. 내 컨트롤러의 newProduct 객체가 뷰의 문제로 인해 채워지지 않은 것을 볼 수 있습니다.
내 주요 질문은 내 textboxes 값을 newData 객체에 어떻게 가져 옵니까?
의견을 보내 주시면 대단히 감사하겠습니다. 고맙습니다.
HomeController.cs :
[HttpPost]
public PartialViewResult RunAddNewProduct(Product newProduct)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Connections.connection;
con.Open();
using (con)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Product VALUES(@Id, @Name, @Description, @Price, @UnitsInStock)", con);
cmd.Parameters.Add(new SqlParameter("@Id", newProduct.Id));
cmd.Parameters.Add(new SqlParameter("@Name", newProduct.Name));
cmd.Parameters.Add(new SqlParameter("@Description", newProduct.Description));
cmd.Parameters.Add(new SqlParameter("@Price", newProduct.Price));
cmd.Parameters.Add(new SqlParameter("@UnitsInStock", newProduct.UnitsInStock));
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
newProduct.Id = Convert.ToInt32(rd.GetInt32(0));
newProduct.Name = Convert.ToString(rd.GetSqlValue(1));
newProduct.Description = Convert.ToString(rd.GetSqlValue(2));
newProduct.Price = Convert.ToDecimal(rd.GetDecimal(3));
newProduct.UnitsInStock = Convert.ToInt32(rd.GetInt32(4));
}
}
return PartialView("AddNewProduct", newProduct);
}
Index.cshtml :
$('#btnConfirmNewProduct').live('click', function() {
var newData = {
'id': $('#txtId').val(),
'name': $('#txtName').val(),
'description': $('#txtDesc').val(),
'price': $('#txtPrice').val(),
'unitsInStock': $('#txtUnitsInStock').val()
};
$.ajax({
url: '/Home/RunAddNewProduct',
data: JSON.stringify(newData),
type: 'POST',
dataType: 'json'
})
.success(function (result) {
$('#products').html(result);
})
.error(function (xhr, status) {
alert(status);
})
});
AddNewProduct.cshtml :
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Units In Stock</th>
</tr>
<tr>
<td><input id="txtAddId" type="text"/></td>
<td><input id="txtAddName" type="text"/></td>
<td><input id="txtAddDesc" type="text"/></td>
<td><input id="txtAddPrice" type="text"/></td>
<td><input id="txtAddUnitsOfStock" type="text"/></td>
</tr>
</table>
<input id="btnConfirmNewProduct" type="button" value="Confirm New Product" />
로버트를 도와 주셔서 감사합니다! – Nick
@ 닉 기쁘게 도와 드릴 수 있습니다 :) – Robert