在asp.net core中,我做了一个服务来添加新行,另一个服务来更新行。我基于JS fetch request
从控制器调用服务。现在我需要从服务响应中返回partialView
和一些Json,如
var data = { htmlContent : '<html table row >', mode : 'insert', isSuccessful : true }
// then when I get response from the controller
.then((data) => {
jsonObj.parse(date);
// ... some logic as follows
if (jsonObj.mode == 'create')
{
if (isSuccessful === 'true') {
// ... appendChild with [jsonObj.htmlContent]
} else {
// ... show modal with [jsonObj.htmlContent]
}
} else if (jsonObj.mode == 'update') {
if (isSuccessful === 'true') {
// ... insertInto (index) with [jsonObj.htmlContent]
} else {
// ... show modal with [jsonObj.htmlContent]
}
}
} else if (jsonObj.mode == 'delete') {
if (isSuccessful === 'true') {
// ... remove element with temp message [jsonObj.htmlContent]
} else {
// ... show modal with [jsonObj.htmlContent]
}
}
});
对于我像这样返回响应类的服务
// service
public addNew()
{
try(){
_dbContext.add(...
var result = _dbContext.saveChanges();
// here is the question
// this is service not ActionResult
// I need to return here html content out of partialView
// along with some other Json data
return new response{htmlContent: partialView(''), mode: 'insert', isSuccessful: true};
}catch
{
return new response{htmlContent: '<h1>something went wrong !</h1>', mode: 'insert', isSuccessful: false};
}
}
public class Response
{
public Dynamic htmlContent { get; set; }
public bool isSuccessful { get; set; }
public Crud mode { get; set; }
}
public enum Crud () {
create, review, update, delete
}
控制器中的我返回给js的addNew result
是Response class
// after injection I use the service here
public IActionResult manage()
{
return _myService.addNew();
}
最后一次可以从微服务返回partialView和一些Json数据,如上面所示
return new response{htmlContent: partialView(''), mode: 'insert', isSuccessful: true};
我认为在没有IActionResult
的情况下返回partialView
是不允许的,但是极客绝对知道
PartialView只能被razor视图解释并解析为HTML。
在你的例子中,你直接从Javascript调用API,所以你没有razor组件来解释PartialView响应。
你要么使用razor视图,要么使用javascript(或jQuery)来创建你想要的html。