HTTP Status 500 - Expected session attribute 'consent' - spring-mvc

this is my html form of consents. after posting the inputs i get error on the browser
<form th:object="${consent}" action="../users/userDetails.html" th:action="#{${#httpServletRequest.servletPath}}" method="post">
<fieldset>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Service Provider</label>
<select id="provider" name="provider" class="form-control" th:onchange="'javascript:showPIIDoc(this.value);'">
<option th:value="0" >Select a Service Provider</option>
<option th:each="provider : ${user.providers}" name="name" th:value="${user.id} +','+ ${provider.id}" th:text="${provider.name}" >[name]</option>
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">PII Document</label>
<select id ="documentdiv" class="form-control">
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Share with</label>
<select class="form-control">
<option th:value="0" >Select a user you want share the document to</option>
<option name="name" th:each="user : ${users}" th:value="${user.id}" th:text="${user.firstName} + ' ' + ${user.lastName}">[name]</option>
</select>
</div>
<div style="clear:both"></div>
<div class="col-sm-7 col-md-6 col-lg-5">
<label for="last_name">Consent</label>
<div style="clear:both"></div>
<input type="checkbox" name="share" th:value="1" th:text="Share" />
</div>
<div style="clear:both"></div>
<div style="margin-top:10px;margin-left:10px" class="form-actions">
<button class="btn btn-primary" type="submit">Add Consent</button>
</div>
</fieldset>
</form>
this is my controller
#RequestMapping(value = "/users/{userId}/providers/{providerId}/documents/{documentId}/consents/new", method = RequestMethod.POST)
public String processNewConsentForm(#PathVariable("userId") int userId, #PathVariable("providerId") int providerId,
#PathVariable("documentId") int documentId, #ModelAttribute("consent") Consent consent, BindingResult result, SessionStatus status) {
User user = this.clinicService.findUserById(userId);
Provider provider = this.clinicService.findProviderById(providerId);
System.out.println("daghade");
System.out.println(provider);
Document doc = this.clinicService.findDocumentById(userId);
Consent c =new Consent();
c.setProvider(provider);
c.setDocument(doc);
c.setUser(user);
c.setStatus(c.getStatus());
c.setFriend(c.getFriend());
System.out.println(c);
if (result.hasErrors()) {
return "providers/createOrUpdateConsentForm";
} else {
this.clinicService.saveConsent(c);
status.setComplete();
return "redirect:/users/{userId}";
}
}
I get this error on the browser
HTTP Status 500 - Expected session attribute 'consent'
after submitting the form
This is the code of Controller for GET Method. it used to call the consent form
#RequestMapping(value = "/users/{userId}/providers/{providerId}/documents/{documentId}/consents/new", method = RequestMethod.GET)
public String initNewConsentForm(#PathVariable("userId") int userId,#PathVariable("providerId") int providerId,#PathVariable("documentId") int documentId, Model model) {
User user = this.clinicService.findUserById(userId);
Provider provider = this.clinicService.findProviderById(providerId);
Document document = this.clinicService.findDocumentById(documentId);
Collection<User> users = this.clinicService.AllUsers();
Consent consent = new Consent();
model.addAttribute("provider",provider);
model.addAttribute("document", document);
model.addAttribute("user", user);
model.addAttribute("users", users);
return "providers/createOrUpdateConsentForm";
}

add model.addAttribute("consent", consent); in your GET method.

Related

Forbidden (CSRF cookie not set.):

i am using ajax to post data from asp (as front) to Django rest api (as backend)
First, I had a problem in Accessing to different domain but it solved using CORS
then i had another error which is related to CSRF
and the error like above :Forbidden (CSRF cookie not set.)
i've used #csrf_exempt to pass this validation but i want a solution for use it without csrf exmption
i tried more than one solution but it's not working or maybe i dont understand the way
Is there any clearly solution to solve it in ajax
In Error 403 ,
'''
JQuery sends " xhr.send( options.hasContent && options.data || null );
'''
i'll include code of my .cshtml file bellow
'''
form id="std_form" class="mx-auto form-horizontal" method="POST" asp-antiforgery="false">
#Html.AntiForgeryToken()
<div class="box-body">
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="first">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="second">
</div>
</div>
<div class=" form-group">
<label for="inputEmail3" class="col-sm-3">ID</label>
<div class="col-md-8">
<input type="number" id="third">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer d-flex">
<button type="submit" id="save_btn" class="btn-success btn">Save</button>
</div>
<!-- /.box-footer -->
</form>
</div>
'''
'''
window.CSRF_TOKEN = "{% csrf_token %}";
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
'''
and this is ajax request
'''
$(document).on('submit', '#std_form', function (e) {
e.preventDefault();
let val1 = parseInt($('#first').val());
let val2 = parseInt($('#second').val());
let val3 = parseInt($('#third').val());
let x={val1,val2,val3};
$.ajax({
type: 'POST',
url: ('http://127.0.0.1:8000/Callfun/processdata/'),
data:{
First: val1,
Second:val2,
Third:val3,
csrfmiddlewaretoken: window.CSRF_TOKEN,
},
success: function (context) {
alert("Wooooooooowwwww");
$('#first').val(context.Max);
$('#second').val(context.Min);
$('#third').val(context.Avg);
},
error: function (context) {
alert("So Bad");
}
})
})
'''

ASP.NET Core 2.1 File Upload Form doesn't reach controller

This is my controller
[ValidateAntiForgeryToken]
[HttpPost("Save")]
public async Task<ActionResult> SaveAsync(UploadDocumentViewModel Input)
{
var filePath = $"{this.hostingEnvironment.WebRootPath}/documents";
foreach(var item in Input.Files)
{
var fileName = ContentDispositionHeaderValue.Parse(item.ContentDisposition).FileName;
var fullFilePath = Path.Combine(filePath, fileName);
using(var stream = new FileStream(fullFilePath, FileMode.Create))
{
await item.CopyToAsync(stream);
}
}
return this.Ok();
}
This is the form that I am uploading from
#using (Html.BeginForm("Save", #ViewContext.RouteData.Values["controller"].ToString(), FormMethod.Post, new { enctype = "multipart/form-data",id = "form" }))
{
#Html.AntiForgeryToken()
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.LabelFor(m => m.Categories)
#Html.DropDownListFor(m => m.Categories, (SelectList)Model.Categories, "", new { #class = "form-control col-sm-12" })
#Html.ValidationMessageFor(m => m.Categories)
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input id="Files" type="file" name="Files" multiple />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="clearfix">
<div class="pull-right">
<input type="submit" id="submit" value="Save" class="btn btn-primary" />
#Html.ActionLink("Cancel", "Index", #ViewContext.RouteData.Values["controller"].ToString(), new { }, new { #class = "btn btn-outline-secondary" })
</div>
</div>
</div>
</div>
</div>
</div>
}
When I am trying to upload my file, I get transferred to a 404 page. However, If I remove the async Task items from my controller, I can reach the controller just fine.
I am trying to follow this Microsoft tutorial but I can't seem to get it to work:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1
Your form is attempting to generate a route for a "Save" action, but you action name is actually SaveAsync. It worked when you removed the async stuff, because you likely changed the method name to Save as well at that point.
It's not traditional to name actions with the Async suffix, even if they are async (unlike other types of methods). As a result, I'd recommend simply removing the Async part of the method name, and you'll be fine. Otherwise, you need to change the reference in your form from "Save" to "SaveAsync" to match the name of the action.
FWIW, you're killing yourself using the HtmlHelper methods here. Use the tag helpers instead. For example, your from could be as simple as:
<form method="post" asp-action="Save" enctype="multipart/form-data">
...
</form>

ASP MVC 6: sending multiselectselect as POST

I have a view in my app, that allows user to set up 2 multiselects.
The problem is: how can I send contents of those multiselects back to controller.
So far I have:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div id="member-list">
<div class="row" id="transfer">
<div class="col-md-6">
<select multiple="multiple" id="right-select">
#foreach (var item in Model.AnotherContacts)
{
<option value="#item.Id" onclick="transfer(this)">
#item.Email - #item.Name
</option>
}
</select>
</div>
<div class="col-md-6">
<select multiple="multiple" id="left-select">
#foreach (var item in Model.Group.Members)
{
<option value="#item.Contact.Id" onclick="transfer(this)">
#item.Contact.Email - #item.Contact.Name
</option>
}
</select>
</div>
</div>
</div>
<div class="col-md-3">
<input type="submit" class="btn btn-grey" value="Save" />
</div>
</div>
And now: how to write a controller to have there list of items, hat I have in both multiselects?
[HttpPost]
public ActionResult Manage(int id)
{
return View();
}
Well first for a form post to be successful you need to add name attributes to your inputs.
<select multiple="multiple" id="left-select" name="leftSelect">
<select multiple="multiple" id="right-select" name="rightSelect">
Then your controller would be
[HttpPost]
public ActionResult Manage(int[] leftSelect, int[] rightSelect)
{
//your code
return View();
}
Notice the names of method parameters are the same as the name attributes on the select lists.
Note: I assumed your #item.Contact.Id and #item.Id are of type
int.
Make your controller expect several parameters
[HttpPost]
public ActionResult Manage(int id, int id2)
{
//your code
return View();
}
This of course depends on what you want to send to to the controller, but I hope you get the idea. You havent shown the code required, but I would guess you have selectLists that return strings, and if that is the case, change the parameters in the Manage Action to expect string variables

AngularJS Firebase Structure

The below image is of the site I created with the fields that get sent to Firebase.
This is how its structured in Firebase, which is as expected
I would like to incorporate the drop boxes so they post above the ID, at the minute in my services.js I have the following:
var ref = new Firebase('leaguesdev.firebaseio.com/League');
But I would like the structure be somthing like
leaguesdev.firebaseio.com/League/dropdown1/dropdown2/Club
I'm not sure how much or how little you need to see but I will attempt to cover what I think you will want to see
services.js
'use strict';
angular.module('myApp.interviews')
.factory('interviewsService', ['$firebase','$firebaseArray','$q', function($firebase, $firebaseArray, $q) {
var ref = new Firebase('leagesdev.firebaseio.com/League');
var getData = function(callback){
return $firebaseArray(ref);
};
var showFalse = function(){
return false;
};
var showTrue = function(){
return true;
};
index.html
<div class="container" ng-controller="LoginCtrl" ng-show="authData">
<div class="row" ng-controller="InterviewsCtrl">
<div class="col-md-5" ng-show="addFormShow">
<h3> Add Clubs to Firebase</h3>
<form name="mainForm" ng-submit="addInterview()" novalidate style="border-color: transparent;">
<div class="form-group">
<label>Division</label>
<select class="form-control" placeholder="Division" ng-model="divisionname" id="dividionname">
<option value="" disabled selected>Please Select Division</option>
<option>Premier Division</option>
<option>Division 1</option>
<option>Division 2</option>
<option>Division 3</option>
<option>Division 4</option>
</select></div>
<div class="form-group">
<label>Club Name</label>
<input type="text" class="form-control" placeholder="Clubname" ng-model="clubname" id="clubname">
</div>

Form validation in meteorjs

I am doing simple validation of inputs in meteorjs, after first tour it works, and every next time it doesn't work (until I reload the page) – it means error messages are not displayed.
//main.js//
Template.addMealForm.events({
'click #submitNewMeal': function (ev) {
ev.preventDefault();
var query = {
name: $("#name").val().trim(),
price: $("#price").val(),
calories: $("#calories").val(),
category: $("#category").val()
};
areInputsValid(query);
}
});
var areInputsValid = function (query) {
if ((query.name.length === 0) || (query.price.length === 0) || (query.calories.length === 0)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("All fields are required");
}
else if ((isNaN(query.price) === true) || (isNaN(query.calories) === true)) {
$("#warningLabel").addClass("di")
$(".warningLabel").text("To Price and Calories fields please enter a number");
}
else {
console.log('it works');
$('.dn').hide();
}
};
//main.html//
<template name="addMealForm">
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control input_form" id="name" placeholder="Name of the meal">
</div>
<div class="form-group">
<label for="price">Price</label>
<input class="form-control input_form" id="price" placeholder="Price">
</div>
<div class="form-group">
<label for="calories">Calories</label>
<input class="form-control input_form" id="calories" placeholder="Calories">
</div>
<div id="warningLabel" class="form-group has-error dn">
<label class="control-label warningLabel"></label>
</div>
<button id="submitNewMeal" type="submit" class="btn btn-rimary">Add</button>
</form>
</template>
The problem is that you are calling $('.dn').hide() in the success case. Because #warningLabel has a class of dn it will not be displayed again on subsequent errors.
One solution is to add $('.dn').show() to the top of areInputsValid.
You already have Tracker as part of Meteor, so I put a little tutorial and JSfiddle together on how to use it to implement a typical form validation scenario.
http://bit.ly/meteor-form-validation-video
http://bit.ly/meteor-form-validation-fiddle

Resources