My ASP.NET MVC & EF project has a base controller as follows:
public class BaseController : Controller
{
private Context _database;
public Context Db
{
get
{
if (_database == null)
{
_database = new Context();
}
return _database;
}
}
protected override void Dispose(bool disposing)
{
if (_database != null)
{
_database.Dispose();
}
base.Dispose(disposing);
}
My ajax save setting code is:
public JsonResult SiteGenelAyarlari(List<GeneralSettings> gs)
{
if (ModelState.IsValid)
{
gs.ForEach(item => Db.GeneralSettings.AddOrUpdate(s => s.LanguageId, item));
Db.SaveChanges();
}
return Json("Saved fine.", JsonRequestBehavior.AllowGet);
}
But when I update a value in the database, after a page refresh the new values do not get pulled. What am I missing?
If I re-run project, new values are being returned fine.
Related
i code a plugin for mybatis generator, but in clientGenerated of extends plugin method doesn't work.
please helpe me ~ ^_^
code is in under:
public class MapperAnnotationPlugin extends PluginAdapter {
private final static Map<String, String> ANNOTATION_IMPORTS;
static {
ANNOTATION_IMPORTS = new HashMap<>();
ANNOTATION_IMPORTS.put("#Mapper", "org.apache.ibatis.annotations.Mapper");
ANNOTATION_IMPORTS.put("#Repository", "org.springframework.stereotype.Repository");
}
private List<String> annotationList;
#Override
public void initialized(IntrospectedTable introspectedTable) {
super.initialized(introspectedTable);
this.annotationList = new ArrayList<>();
Properties properties = this.getProperties();
boolean findMapper = false;
for (Object key : properties.keySet()) {
String keyStr = key.toString().trim();
if (keyStr.startsWith("#Mapper")) {
findMapper = true;
}
if (StringUtility.isTrue(properties.getProperty(key.toString()))) {
annotationList.add(keyStr);
}
}
if (!findMapper) {
annotationList.add(0, "#Mapper");
}
}
#Override
public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {
super.clientGenerated(interfaze, introspectedTable);
for (String annotation : annotationList) {
if ("#Mapper".equals(annotation)) {
if (introspectedTable.getTargetRuntime() == IntrospectedTable.TargetRuntime.MYBATIS3) {
interfaze.addImportedType(new FullyQualifiedJavaType(ANNOTATION_IMPORTS.get(annotation)));
interfaze.addAnnotation(annotation);
}
} else if (Objects.nonNull(ANNOTATION_IMPORTS.get(annotation))) {
logger.info(PluginConst.TEACHEE_PLUGIN + "添加" + annotation);
interfaze.addImportedType(new FullyQualifiedJavaType(ANNOTATION_IMPORTS.get(annotation)));
interfaze.addAnnotation(annotation);
}
}
return true;
}
}
in second method, in debug, it had not go this method, so what could i do in next step
Same problem when I maked a plugin for mybatis-generator-plugin. The method of clientGenerated didnot be callback. It is my way, call from another method which include Interface object.
#Override
public boolean clientCountByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
this.clientGenerated(interfaze, null, introspectedTable);
return false;
}
Both generator-core/generator-plugin version is 1.4.0, work fine now.
https://github.com/mybatis/generator/releases/tag/mybatis-generator-1.4.0
So, I migrated my RestAPI project to ASP.NET Core 3.0 from ASP.NET Core 2.1 and the HttpPost function that previously worked stopped working.
[AllowAnonymous]
[HttpPost]
public IActionResult Login([FromBody]Application login)
{
_logger.LogInfo("Starting Login Process...");
IActionResult response = Unauthorized();
var user = AuthenticateUser(login);
if (user != null)
{
_logger.LogInfo("User is Authenticated");
var tokenString = GenerateJSONWebToken(user);
_logger.LogInfo("Adding token to cache");
AddToCache(login.AppName, tokenString);
response = Ok(new { token = tokenString });
_logger.LogInfo("Response received successfully");
}
return response;
}
Now, the login object has null values for each property. I read here, that
By default, when you call AddMvc() in Startup.cs, a JSON formatter, JsonInputFormatter, is automatically configured, but you can add additional formatters if you need to, for example to bind XML to an object.
Since AddMvc was removed in aspnetcore 3.0, now I feel this is why I am unable to get my JSON object anymore. My Startup class Configure function looks like this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseRouting();
//app.UseAuthorization();
//app.UseMvc(options
// /*routes => {
// routes.MapRoute("default", "{controller=Values}/{action}/{id?}");
//}*/);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}
The request I am sending through postman (raw and JSON options are selected)
{
"AppName":"XAMS",
"licenseKey": "XAMSLicenseKey"
}
UPDATES
Postman Header: Content-Type:application/json
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//_logger.LogInformation("Starting Log..."); //shows in output window
services.AddSingleton<ILoggerManager, LoggerManager>();
services.AddMemoryCache();
services.AddDbContext<GEContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers();
services.AddRazorPages();
//Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://localhost:44387/";
options.Audience = "JWT:Issuer";
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(5);
options.RequireHttpsMetadata = false;
});
services.AddAuthorization(options =>
{
options.AddPolicy("GuidelineReader", p => {
p.RequireClaim("[url]", "GuidelineReader");
});
});
//
}
Application.cs
public class Application
{
public string AppName;
public string licenseKey;
}
With you updated code, I think the reason is you didn't create setter for your properties.
To fix the issue, change your Application model as below:
public class Application
{
public string AppName {get;set;}
public string licenseKey {get;set;}
}
cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'
code
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json(new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
The second parameter for Json method in Web API controller is incorrectly assigned, since ApiController Json method requires JsonSerializerSettings as second argument:
protected internal JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings)
{
......
}
The MVC controller counterpart for Json method is shown below:
protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
......
}
In this case, if the controller class containing Get method above extends ApiController, you need to change 2 return Json statements to return new JsonResult as given below:
public class ControllerName : ApiController
{
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
// return JsonResult here
return new JsonResult()
{
Data = new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate }},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
catch (Exception Ex)
{
}
// return JsonResult here
return new JsonResult()
{
Data = new { success = false },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
If you want to use MVC controller when returning JSON instead, change ApiController to Controller class from System.Web.Mvc namespace and keep return Json(...) there.
Similar issue:
JSON return error with ASP
My problem is about this primefaces tag:
<p:selectManyCheckbox id="datasourceGroup" value="#{sessionBean.datasourceGroups}" converter="datasourceGroupConverter">
<f:selectItems value="#{sesionBean.getAllDatasourceGroups()}" var="group" itemLabel="#{group.toString()}" itemValue="#{group}" />
</p:selectManyCheckbox>
It does not render any visible output (checkboxes) at all. From logging output i know that the 'sessionBean.getAllDatasourceGroups()' method is not even called once during page refresh. only the 'sessionBean.getDatasourcegroups()' getter for the 'datasourceGroups' property is called once.
And i can't figure out what the problem is. I have very similar usecases of <p:selectManyMenu> and <p:selectOneMenu> on the same page and they work fine. So i have a basic understanding of how this works...or so i thought :-)
here are the other relevant parts of the code for reference:
SessionBean:
#ManagedBean
#SessionScoped
public class SessionBean implements Serializable {
private List<DatasourceGroup> datasourceGroups = new ArrayList<>();
public List<DatasourceGroup> getDatasourceGroups() {
return datasourceGroups;
}
public void setDatasourceGroups(List<DatasourceGroup> datasourceGroups) {
this.datasourceGroups = datasourceGroups;
}
public List<DatasourceGroup> getAllDatasourceGroups() {
List<DatasourceGroup> list = Arrays.asList(DatasourceGroup.values());
return list;
}
}
DatasourceGroup Enum:
public enum DatasourceGroup {
KUNDEN (Permission.ZugriffKunden),
INKASSO (Permission.ZugriffInkasso),
INTERESSENTEN (Permission.ZugriffInteressenten),
WARN (Permission.ZugriffWarnadressen);
private Permission permissionNeeded;
DatasourceGroup(Permission permission) {
this.permissionNeeded=permission;
}
public Permission getPermissionNeeded() {
return permissionNeeded;
}
}
And the DatasourceGroupConverter:
#FacesConverter("datasourceGroupConverter")
public class DatasourceGroupConverter implements Converter {
#Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if (Toolbox.isNullOrEmpty(value))
return null;
try {
return DatasourceGroup.valueOf(value);
} catch (IllegalArgumentException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error:",
"'" + value + "' is not a valid datasource group name"));
}
}
#Override
public String getAsString(FacesContext fc, UIComponent uic, Object object) {
if(object != null && object instanceof DatasourceGroup) {
return ((DatasourceGroup)object).toString();
}
return null;
}
}
I'm using primefaces 6.0 by the way.
public ActionResult MyActionMethod(MyModel model)
{
//some code
string myVar= ActionMethod2(model).toString();
//use myVar
Method3(myVar, otherVar);
}
public ActionResult ActionMethod2()(MyModel model)
{
return View(model);
}
private Method3(string myVar, int otherVar)
{
//do something;
}
As sample code, above, I have a method that returns .cshtml view, called ActionMethod2.
I want to use the returned html as a string variable in my action method.How is that possible?
You can use Content Method for this.
public ActionResult ActionMethod2()
{
return Content("YourHTMLString");
}
Or you can set return type as string and pass your HTML string.
public string ActionMethod2()
{
return "<html></html>";
}
First Mistake is ActionMethod2 return View, And you can get it directly from MyActionMethod
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public ActionResult MyActionMethod(MyModel model)
{
//some code
//string myVar= ActionMethod2(model).toString();
var myVar = RenderPartialViewToString("yourviewName", model);
//use myVar
Method3(myVar, otherVar);
}
try this and it will work with you.
Approach One could be pass your wanted params as part of the routeValues parameter of the RedirectToAction() method.Using Query string data passed.
Or you can frame it with the help of query strings like:
return RedirectToAction( "Main", new RouteValueDictionary(
new { controller = controllerName, action = "YourActionName", Id = Id}) );
Or You can make use of TempData:
[HttpPost]
public ActionResult MyActionMethod(MyModel model)
{
TempData["myModal"]= new MyModel();
return RedirectToAction("ActionMethod2");
}
[HttpGet]
public ActionResult ActionMethod2()
{
MyModel myModal=(MyModel)TempData["myModal"];
return View();
}
In the URL bar of the browser.
This solution uses a temporary cookie:
[HttpPost]
public ActionResult Settings(SettingsViewModel view)
{
if (ModelState.IsValid)
{
//save
Response.SetCookie(new HttpCookie("SettingsSaveSuccess", ""));
return RedirectToAction("Settings");
}
else
{
return View(view);
}
}
[HttpGet]
public ActionResult Settings()
{
var view = new SettingsViewModel();
//fetch from db and do your mapping
bool saveSuccess = false;
if (Request.Cookies["SettingsSaveSuccess"] != null)
{
Response.SetCookie(new HttpCookie("SettingsSaveSuccess", "") { Expires = DateTime.Now.AddDays(-1) });
saveSuccess = true;
}
view.SaveSuccess = saveSuccess;
return View(view);
}
Or try Approach 4:
Just call the action no need for redirect to action or the new keyword for model.
[HttpPost]
public ActionResult MyActionMethod(MyModel myModel1)
{
return ActionMethod2(myModel1); //this will also work
}
public ActionResult ActionMethod2(MyModel myModel)
{
return View(myModel);
}