SOLVED
We've solved it. The form that the backend requires data was param, so the form that the vue sends was changed to param, not data!
I'm making a password change page.
Meanwhile, I got an error that there was no old password, new password data but I definitely transferred the data from Vue through axios.
There were answers to 'required=false', so I tried oldpassword, but here's the result.
However, we took 'required= true' because we believe newpassword, oldpassword is essential data for this approach.
When using post-man or swagger, the password is changed signaling 200 normally.
I thought there might be a problem with 'patch', so I tried 'put', but the error didn't change.
frontend
<div class="input-with-label">
<input v-model="newpassword" id="newpassword" placeholder="새 비밀번호를 입력하세요." :type="passwordType" />
<label for="newpassword">새 비밀번호</label>
<div class="error-text" v-if="error.newpassword">{{error.newpassword}}</div>
</div>
<form #submit.prevent="changepassword" #submit="checkForm">
<div v-if="activeButton() && !isSubmit">
<!-- <button #click="PopUpEmailModal" class="btn-bottom" >가입하기</button> -->
<button class="btn-bottom">변경하기</button>
</div>
<div v-else>
<button class="btn-bottom disabled" >변경하기</button>
</div>
</form>
import axios from 'axios'
export default {
name:'ChangePassword',
data: ()=> {
return{
email:"",
oldpassword:"",
newpassword:"",
isSubmit: true,
error: {
newpassword: false,
},
passwordType: "password",
passwordSchema: new PV(),
}
},
created() {
this.passwordSchema
.is()
.min(8)
.is()
.max(100)
.has()
.digits()
.has()
.letters();
},
watch: {
newpassword: function(v) {
this.checkForm();
},
},
methods:{
changepassword(){
axios({
url:'http://127.0.0.1:8080/account/changePassword',
method:'patch',
data:{
email: this.email,
oldPassword: this.oldpassword,
newPassword: this.newpassword,
},
})
.then(res=>{
console.log(res)
this.$router.push({ name:'Login' })
})
.catch(err=>{
console.log(typeof this.oldpassword)
console.log(this.oldpassword)
console.log(this.newpassword)
console.log(this.email)
console.log(err)
})
},
}
backend
#PatchMapping("/account/changePassword")
#ApiOperation(value = "비밀번호변경")
public Object changePassword(#RequestParam(required = false) final String oldPassword,
#RequestParam(required = true) final String newPassword,
#RequestParam(required = true) final String email){
Optional<User> userOpt = userDao.findByEmail(email);
if(!passwordEncoder.matches(oldPassword, userOpt.get().getPassword())){
throw new IllegalArgumentException("잘못된 비밀번호입니다.");
}
User user = new User(userOpt.get().getUid(), userOpt.get().getNickname(), email,
passwordEncoder.encode(newPassword), userOpt.get().getIntroduction(), userOpt.get().getThumbnail(), userOpt.get().getRoles());
userDao.save(user);
final BasicResponse result = new BasicResponse();
result.status = true;
result.data = "success";
ResponseEntity response = null;
response = new ResponseEntity<>("OK", HttpStatus.OK);
return response;
}
I believe you are using #RequestParam annotations but you are not sending any params in the URL from the frontend, hence the 400 error.
Since you are using Patch/Put I would suggest you change your changePassword function to take a dto. And since you are already sending data in the body from frontend so no change needed there.
For example
public Object changePassword(#RequestBody #Valid ChangePasswordDto changePasswordDto){
// your logic
}
Then create a ChangePasswordDto class with #Required on properties that are required.
public class ChangePasswordDto{
private String email;
private String newPassword;
private String oldPassword;
#Required
public void setEmail(String email) {
this.email= email;
}
#Required
public void setOldPassword(String oldPassword) {
this.oldPassword= oldPassword;
}
#Required
public void setNewPassword(String newPassword) {
this.newPassword= newPassword;
}
// corresponding getters
}
I want to update some data of my database. For that I'm using an ajax request that will change the value of one variable. However this put request isn't working, going straight to the error and giving me an error 500 in the console. Can someone understand why this is happening?
Here is my ajax request:
function atualizaBD(idmarcador, novoEstado) {
$.ajax
({
url: `/api/IgnicoesAPI/${idmarcador}`,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
Id: +idmarcador,
Estado: novoEstado
}),
success: function (result) {
alert(result);
},
error: function () {
alert("ocorreu um erro!")
}
});
}
Here is the PUT in my controller:
[HttpPut("{id}")]
public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao, string novoEstado)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ignicao.Id)
{
return BadRequest();
}
var dataDecisao = DateTime.Now;
var ig = _context.Ignicoes.FirstOrDefault (ignicaoId => ignicaoId.Id.Equals(id));
if (ig != null)
{
ig.Estado = novoEstado;
ig.Latitude = ignicao.Latitude;
ig.Longitude = ignicao.Longitude;
//esta data vai depender da avaliação de cada uma das ocorrencias
ig.DataInicioPropostaIgnicao = ignicao.DataInicioPropostaIgnicao;
//esta data é colocada quando é definido o estado da ignição (aceite, recusado, em avaliação, concluido)
ig.DataDecisaoIgnicao = dataDecisao;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IgnicoesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
The variable that I want to change is Estado to novoEstado
First of all, you're building an Ignicoes object in your AJAX request like this:
{
Id: +idmarcador,
Estado: novoEstado
}
Then you're updating properties from it on the server like this:
ig.Latitude = ignicao.Latitude;
ig.Longitude = ignicao.Longitude;
ig.DataInicioPropostaIgnicao = ignicao.DataInicioPropostaIgnicao;
Since you're not setting properties Latitude, Longitude, or DataInicioPropostaIgnicao when you build the Ignicoes object in your AJAX request, they will always be null here.
Second, you are setting the Estado property in the AJAX request, so you would want to do this on the server:
ig.Estado = ignicao.Estado;
Then you can remove the string novoEstado parameter from your PutIgnicoes method completely.
If you want to keep the string novoEstado parameter, you need to change to something like [FromQuery] string novoEstado then change your AJAX request to use:
url: `/api/IgnicoesAPI/${idmarcador}?novoEstado=${novoEstado}`
I suspect the string novoEstado parameter is coming into the PutIgnicoes method as null (since it's not defined as a query or route parameter). If it is a non-nullable foreign key, the your call to SaveChangesAsync wil fail with a foreign key constraint error.
this is a followup question to the one here Using $.ajax to send data via HttpPost in aspnet5, is not working
I have made the changes requested in the comments and a few other changes such as using the Json package from Newtonsoft.
Basically I have a column, and when you click the header a couple of input tags appear dynamically, to change column name and submit it. I want to change it and show it right away using ajax. The code to do this is below, and sorry but the code is in coffee script. Also I am using ASPNET5 RC1 with MVC6.
SumbitColumnForm = () ->
$('.panel-heading').on 'click', 'input.ColumnTitleSumbit', (event) ->
event.preventDefault();
columnName = $('.NewColumnName').val().trim()
columnNumber = $(this).parent().parent().attr 'id'
$.ajax
url: '/Board/ChangeColumnName',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ColumnName: columnName, ColumnNumber: columnNumber})
success: (data) ->
alert "Hit the Success part"
alert 'data is' + data
panelHeading = $('input.ColumnTitleSubmit').parent()
$(panelHeading).html("<h3 class='panel-title'> <h3>").text(data)
error: (xhr, err) ->
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
The relevant action methods from the controller are below
[Route("{p_BoardName}")]
public IActionResult Show(string p_BoardName)
{
m_Board.BoardName = p_BoardName;
ViewData["BoardName"] = m_Board.BoardName;
return View(m_Board);
}
[HttpPost]
public JsonResult ChangeColumnName(string newColumnData)
{
ColumnModel column = JsonConvert.DeserializeObject<ColumnModel>(newColumnData);
// Update column name in the board model, the board model stores a list of columns
m_Board.ColumnList[column.ColumnNumber].ColumnName = column.ColumnName;
var json = JsonConvert.SerializeObject( m_Board.ColumnList[column.ColumnNumber]);
return Json(json);
}
Also the column and board models are below
public class ColumnModel
{
private string m_name;
private int m_columnNumber;
public int ColumnNumber { get { return m_columnNumber; } set {m_columnNumber = value;} }
public string ColumnName { get { return m_name;} set { m_name = value; } }
public ColumnModel(string p_Name, int p_ColumnNumber)
{
m_name = p_Name;
m_columnNumber = p_ColumnNumber;
}
public ColumnModel() { }
}
public class BoardModel
{
private string m_BoardName;
private List<ColumnModel> m_ColumnList;
[Required]
public string BoardName { get { return m_BoardName; } set { m_BoardName = value; } }
public List<ColumnModel> ColumnList
{
get { return m_ColumnList; }
set { m_ColumnList = value; }
}
}
I have done a lot of googling and I still can't get this to work. The request is not hitting the success attribute and is hitting the error attribute. I still get a 200 status code to show it is OK, and for some reason my data is a long html file, or in this case the 'Show' view from the board controller. I have requested requested Json and I am getting html. I don't know what is going on, I feel what might be going wrong is the http post method ChangeColumnName in the controller. Maybe I am not receiving or sending a valid JSON object. Any help will be greatly appreicated.
The key here is [ValidateInput(false)]
Try this :
Rather than sending a JSON.stringify, just send it as an object which means
var Data = {ColumnName: columnName, ColumnNumber: columnNumber};
You were already doing this from your link!
Change your signature to receive your ColumnModel directly rather than a string and add the attribute [ValidateInput(false)] to your action. You'll not need to deserialize with this approach!
[ValidateInput(false)]
public JsonResult ChangeColumnName(ColumnModel newColumnData)
{
Console.WriteLine(newColumnData.ColumnName);
}
Let me know if this solves your problem!
You are supplying the correct variable
in ajax
data: {ColumnName: columnName, ColumnNumber: columnNumber}
In controller
[HttpPost]
public JsonResult ChangeColumnName(string ColumnName, int ColumnNumber)
{
..your code..
}
hope this helps
Can't pass ModelState validation in WebApi application for object which contains nullable types and has null values. The error message is "The value 'null' is not valid for DateProperty."
The code of object:
public class TestNull
{
public int IntProperty { get; set; }
public DateTime? DateProperty { get; set; }
}
Controller:
public class TestNullController : ApiController
{
public TestNull Get(int id)
{
return new TestNull() { IntProperty = 1, DateProperty = null };
}
public HttpResponseMessage Put(int id, TestNull value)
{
if(ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.OK, value);
else
{
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (var keyValue in ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
}
Request:
$.getJSON("api/TestNull/1",
function (data) {
console.log(data);
$.ajax({
url: "api/TestNull/" + data.IntProperty,
type: 'PUT',
datatype: 'json',
data: data
});
});
I just did a quick test in one my own WebAPI projects and passing null as a value for a nullable value-type works fine. I suggest you inspect the actual data that is being send to your server using a tool like Fiddler
Two valid scenarios that will work are:
{ IntProperty: 1, DateProperty: null }
{ IntProperty: 1 } // Yes, you can simply leave the property out
Scenarios that will NOT work are:
{ IntProperty: 1, DateProperty: "null" } // Notice the quotes
{ IntProperty: 1, DateProperty: undefined } // invalid JSON
{ IntProperty: 1, DateProperty: 0 } // Will not be properly interpreted by the .NET JSON Deserializer
If the two default scenario's do not work then I suspect your problem lies elsewhere. I.e. Have you changed any of the default settings of the JSON serializer in your global.asax?
Almost 9 years later I'm still having similar problem in ASP.NET Core 3.1
But I've found a working workaround for me (just exclude null values from data being sent - as opposed to sending values as nulls).
See https://stackoverflow.com/a/66712465/908608
It's not a real solution, becasue backend still does not handle null values properly, but at least ModelState validation does not fail for nullable properties.
OS: Windows Vista, Framework: Jqgrid (latest), Spring (latest), JQuery (latest)
I am using Jqgrid to post a form to Spring Controller to persist. When the Spring controller tries to auto bind the request parameters to domain object, it throws exception when trying to bind 'Date' data type. I am using JSon format for transfer data. The Jqgrid display the date correctly. The transfer string contains '&-quot;' characters before and after the date that causes the exception. I dont know how to remove the escape character from Jqgrid. I dont know how to intercept the string before Spring gets a chance to auto bind. Thanks for your help in advance.
public class JsonDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AtOverride
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
My controller class has initBinder method.
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
Exception stack trace
nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2010-12-01 11:10:00" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException]
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:820)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:359)
I will try to set-up a tutorial on my blog if I get the time today.
My JSP file is just a simple JSP file with your typical JqGrid declaration:
<script type="text/javascript">
jq(function() {
// This is the grid
jq("#grid").jqGrid({
url:'/myapp/users',
datatype: 'json',
mtype: 'GET',
colNames:['Id','Username','First Name'],
colModel:[
{name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10},hidden:true},
{name:'firstName',index:'firstName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}, editrules:{required:true}},
{name:'lastName',index:'lastName', width:80, align:"right",editable:true, editrules:{required:true}, editoptions:{size:10}, editrules:{required:true}}
],
postData: {
// Here you can post extra parameters
// For example using JQuery you can retrieve values of other css elements
},
rowNum:10,
rowList:[10,20,30],
height: 200,
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption:"Users",
emptyrecords: "Empty records",
loadonce: false,
loadComplete: function() {
// Here you can provide extra functions after the grid is loaded completely
// Like auto-height function
},
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "id"
}
});
// This is the pager
jq("#grid").jqGrid('navGrid','#pager',
{edit:false,add:false,del:false,search:true},
{ },
{ },
{ },
{
sopt:['eq', 'ne', 'lt', 'gt', 'cn', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true }
);
// Custom Add button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Add",
buttonicon:"ui-icon-plus",
onClickButton: addRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Custom Edit button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Edit",
buttonicon:"ui-icon-pencil",
onClickButton: editRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Custom Delete button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Delete",
buttonicon:"ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Toolbar Search
jq("#grid").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : true, defaultSearch:"cn"});
});
Take note I'm using JQuery's noConflict method here. Since I have another Javascript framework that uses the $, I forced JQuery to use a different identifier for itself. I picked jq and here's the declaration:
<script type="text/javascript">
var jq = jQuery.noConflict();
</script>
The Javascript's above can be declared on the head section of your JSP. The critical part of the JqGrid declaration is the jsonReader and the datatype. Make sure the colModel name matches your model properties.
You could probably use StringTrimmerEditor's second constructor to delete those extra chars
StringTrimmerEditor(String charsToDelete, boolean emptyAsNull)
Based on the Spring docs:
charsToDelete - a set of characters to delete, in addition to trimming an input String. Useful for deleting unwanted line breaks. E.g. "\r\n\f" will delete all new lines and line feeds in a String.
I also use the latest version of JqGrid and Spring 3, but the way I handled the parameters seems to be simpler. Here's how I did it:
#Controller
#RequestMapping("/json")
public class JsonController {
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody JsonResponse getAll(
#RequestParam("_search") String search,
#RequestParam(value="filters", required=false) String filters,
#RequestParam(value="datefrom", required=false) String datefrom,
#RequestParam(value="dateto", required=false) String dateto,
#RequestParam(value="page", required=false) String page,
#RequestParam(value="rows", required=false) String rows,
#RequestParam(value="sidx", required=false) String sidx,
#RequestParam(value="sord", required=false) String sord
) { ... }
All parameters are passed as normal Strings. The datefrom and dateto are custom parameters I passed from the JqGrid. The date comes from a JQuery's DatePicker and passed via JqGrid postData:
postData: {
datefrom: function() { return jq("#datepicker_from").datepicker("getDate"); },
dateto: function() { return jq("#datepicker_to").datepicker("getDate"); }
},
JsonResponse is a simple POJO that I used to map the search parameters passed by a JqGrid:
public class JsonResponse {
/**
* Current page of the query
*/
private String page;
/**
* Total pages for the query
*/
private String total;
/**
* Total number of records for the query
*/
private String records;
/**
* An array that contains the actual data
*/
private List<MyDTO> rows;
public JsonResponse() {
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getRecords() {
return records;
}
public void setRecords(String records) {
this.records = records;
}
public List<MyDTO> getRows() {
return rows;
}
public void setRows(List<MyDTO> rows) {
this.rows = rows;
}
}
MyDTO is a simple DTO object as well.
In my Spring applicationContext.xml, I just have to declare the following:
<mvc:annotation-driven/>
And added the Jackson jar for converting from JSON to POJO and vice versa
To convert the String date to a real Date, I used the great Joda library. But of course, you can use JDK's standard Date.
If you notice on my JSP, I added custom buttons. The onClickButton calls another Javascript function. For example on the Add button, I have the addRow function. Here's the function declaration:
function addRow() {
// Get the currently selected row
jq("#grid").jqGrid('editGridRow','new',
{ url: "/myapp/users/add",
editData: {
// Here you add extra post parameters
},
recreateForm: true,
beforeShowForm: function(form) {
// Here you can add, disable, hide elements from the popup form
},
closeAfterAdd: true,
reloadAfterSubmit:false,
afterSubmit : function(response, postdata)
{
// This is a callback function that will evaluate the response sent by your Controller
var result = eval('(' + response.responseText + ')');
var errors = "";
if (result.success == false) {
// Do whatever you like if not successful
} else {
// Do whatever you like if successful
}
// only used for adding new records
var new_id = null;
// Then this will be returned back to the popup form
return [result.success, errors, new_id];
}
});
}
Take note of the url:
url: "/myapp/users/add"
This is the mapping to your Controller that handles the add request
Now, for the Jackson serialization/deserialization, you'll be suprised how easy it is.
First, make sure you have the latest Jackson library in your classpath. Next, open your Spring xml config, and add the following:
<mvc:annotation-driven/>
That's it :)
Make sure you have the latest dependency jars. I use Spring 3.0.4. There's 3.0.5 already. Also, make sure you have the latest aspectjweaver.jar. If you wanna know what's inside that mvc-annotation-driven tag, just search the web and you'll see what it contains. Basically it automatically declares an HTTPMessageConverter for JSON, and uses Jackson by default.
For the Controller, here's the mapping to the /myapp/users/add request:
#Controller
#RequestMapping("/myapp/users")
public class UserController {
#RequestMapping(value = "/add", method = RequestMethod.POST)
public #ResponseBody JsonGenericResponse addAsJson(
#RequestParam("id") String id,
#RequestParam("firstName") String firstName,
#RequestParam("lastName") String lastName
) {
// Validate input
// Process data. Call a service, etc.
// Send back a response
// JsonGenericResponse is a custom POJO
// Jackson will automatically serialize/deserialize this POJO to a JSON
// The #ResponseBody annotation triggers this behavior
JsonGenericResponse response = new JsonGenericResponse();
response.setSuccess(false);
response.setMessage("Error in server");
return response;
}
}
Here's the JsonGenericResponse:
public class JsonGenericResponse {
private Boolean success;
private List<String> message;
public JsonGenericResponse() {
message = new ArrayList<String>();
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<String> getMessage() {
return message;
}
public void setMessage(String message) {
this.message.add(message);
}
}
It's just really a simple POJO.
In your JSP, to process the response, you use JavaScript in your JqGrid. The response will be sent back to whomever the caller (the add form in this case). Here's a sample JavaScript that will process the response:
if (result.success == false) {
for (var i = 0; i < result.message.length; i++) {
errors += result.message[i] + "<br/>";
}
} else {
jq("#dialog").text('Entry has been edited successfully');
jq("#dialog").dialog(
{ title: 'Success',
modal: true,
buttons: {"Ok": function() {
jq(this).dialog("close");}
}
});
}
return [result.success, errors, null];