鉴于这些C#对象
class foo
{
int fooId {get; set;}
string fooName {get;set;}
List<bar> bars {get; set;}
}
class bar
{
int barId {get; set;}
string barName {get;set;}
}
和WebApi方法
[HttpPost]
public HttpResponseMessage AddFooBar(foo model)
{
//...
}
假设我们有一个表单,用户输入fooName和一个条形项列表,从表单序列化数据并将其提交给WebApi方法的最佳方法是什么?
答案 0 :(得分:0)
我强烈建议您使用
创建一个哑视图<form id="f">
@Html.TextBoxFor(x=>x.foo);
@for(var i = 0; i<Model.foo.bars.Length; i++){
@Html.TextBoxFor(x=>x.foo.bars[i]);
}
</form>
$(document).ready(function(){
console.log($('#f').serialize());
});
所以你可以看到预期的结构。那么您可以按照自己的意愿填写JSON
答案 1 :(得分:0)
我找不到在一个ajax调用和一个WebApi控制器操作中发布foo和bar列表的方法。我以两个ajax帖子和两个控制器动作结束。两次旅行而不是一次但是有效。以下是我的解决方案,以防任何人发现它有用。
在HTML方面,我使用了两个div作为表单,因为这是Asp.net webforms,这意味着我们只限于一个表单。
<div id="foo-form">
<input type="text" name="fooName" value="" />
<button type="button" class="btn-cancel">Cancel</button>
<button type="button" class="btn-submit">Submit</button>
</div>
<div id="bar-form">
<input type="text" class="foobar" value="" />
<input type="text" class="foobar" value="" />
<input type="text" class="foobar" value="" />
<input type="text" class="foobar" value="" />
</div>
Javascript方面(使用Jquery ajax)
$("#foo-form .btn-submit").click(function (e) {
e.preventDefault();
fooBar.saveFoo();
});
var fooBar = new function () {
//this posts foo
this.saveFoo = function () {
// serialize the form
var serializedData = $("#foo-form :input").serialize();
$.ajax({
type: "POST",
url: "/myapp/api/FooBar/AddFoo",
data: serializedData,
cache: false
}).done(function (data) {
if (data["Status"] === 'success') {
//pass the id to the saveBars function
fooBar.saveBars(data["Id"])
}
else {
//handle logic error
}
}).fail(function (xhr, textStatus, errorThrown) {
//handle ajax error
}).always(function () {
//something to do always
});
}
//this posts bars
this.saveBars = function (fooId) {
//save all bars in array
var arrBars = [];
$('#bar-form .foobar').each(function () {
arrBars.push(
{
"fooId": fooId,
"fooName": $(this).val()
}
);
});
$.ajax({
type: "POST",
url: "/myapp/api/FooBar/AddBars",
data: JSON.stringify(arrBars),
cache: false,
contentType: "application/json; charset=utf-8"
}).done(function (data) {
if (data["Status"] === 'success') {
//show success message
}
else {
//handle logic error
}
}).fail(function (xhr, textStatus, errorThrown) {
//handle ajax error
}).always(function () {
//something to do always
});
}
}
现在在服务器端webapi控制器C#代码
[HttpPost]
public HttpResponseMessage AddFoo(Foo model)
{
try
{
//validate
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "error", Message = "Error in foo"});
//save foo
var db = new FooBarDB();
var id = db.AddFoo(model);
//return new fooId
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "success", Id = id });
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
[HttpPost]
public HttpResponseMessage AddBars(List<Bar> bars)
{
try
{
//validate bars
if (!this.ValidateBars(bars))
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "error", Message = "Errors in bars"});
//save bars
var db = new FooBarDB();
db.AddBars(bars);
//show success
return Request.CreateResponse(HttpStatusCode.OK, new { Status = "success"});
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
private bool ValidateBars(List<Bar> bars)
{
//logic to validate bars
}