C# 如何将不同的模型(未声明)从视图发送到控制器?
我有一张产品表。如果单击了C# 如何将不同的模型(未声明)从视图发送到控制器?,c#,html,asp.net-mvc,C#,Html,Asp.net Mvc,我有一张产品表。如果单击了btnAdd,我将尝试在表的顶部添加新的输入。然后按Save a向控制器发送数据。我知道如果我提交,它会将声明的数据类型发送到视图顶部的控制器。在我的例子中,IndexViewModel。但是我想把产品模型的一个实例发送回控制器 我有一个控制器: public class ProductController : Controller { public ActionResult Index() { IndexViewModel
btnAdd
,我将尝试在表的顶部添加新的输入。然后按Save a向控制器发送数据。我知道如果我提交,它会将声明的数据类型发送到视图顶部的控制器。在我的例子中,IndexViewModel
。但是我想把产品
模型的一个实例发送回控制器
我有一个控制器:
public class ProductController : Controller
{
public ActionResult Index()
{
IndexViewModel _IndexViewModel = new IndexViewModel()
// some code
return View(_IndexViewModel );
}
[HttpPost]
public ActionResult Insert(Product product)
{
// some code
}
}
两种型号:
public class IndexViewModel
{
public List<Product> Products { get; set; }
}
和视图:
@model TestApp.ViewModels.IndexViewModel
@{
ViewBag.Title = "Index";
}
<div>
<input type="button" value="btnAdd"/>
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th/>
</tr>
</thead>
<tbody>
<tr class="new-row" hidden>
@using (Html.BeginForm("Insert", "Product", FormMethod.Post))
{
<td><input type="text" id="newProductName"/></td>
<td><input type="text" id="newProductPrice"/></td>
<td><input type="text" id="newProductQuantity"/></td>
<td>
<input type="submit" id="btnSave" value="Save"/>
</td>
}
</tr>
@foreach (var product in Model.Products)
{
<tr>
<td>@product.Name"</td>
<td>@product.Price"</td>
<td>@product.Quantity"</td>
</tr>
}
</tbody>
</table>
</div>
有没有办法将
产品
模型传递到插入
操作?您只需要添加与产品
类的属性相同的名称,而不需要jquery AJAX
@using (Html.BeginForm("Insert", "Product", FormMethod.Post))
{
<td><input type="text" id="newProductName" name="Name" /></td>
<td><input type="text" id="newProductPrice" name="Price" /></td>
<td><input type="text" id="newProductQuantity" name="Quantity" /></td>
<td>
<input type="submit" id="btnSave" value="Save" />
</td>
}
@使用(Html.BeginForm(“插入”、“产品”、FormMethod.Post))
{
}
这将帮助您理解您的意思“但它不起作用”?您是否尝试过用[JsonResult]标记控制器?还有,你有什么错误吗?您是否在服务器上收到请求,但您的模型未绑定或路由未配置?您可以通过使用Global.asax并使用ModelBinders.Binders.Add(,)注册函数来检查它
function save() {
var newProduct = {};
newProduct.Name = $('#newProductName').val();
newProduct.Price = $('#newProductPrice').val();
newProduct.Quantity = $('#newProductQuantity').val();
$.ajax({
url: "Product/Insert",
type: 'post',
data: '{product: ' + JSON.stringify(newProduct) + '}',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response) {
alert("Success");
},
error: function (xhr, status, error) {
alert("Failed");
}
})
}
@using (Html.BeginForm("Insert", "Product", FormMethod.Post))
{
<td><input type="text" id="newProductName" name="Name" /></td>
<td><input type="text" id="newProductPrice" name="Price" /></td>
<td><input type="text" id="newProductQuantity" name="Quantity" /></td>
<td>
<input type="submit" id="btnSave" value="Save" />
</td>
}