ASP.NET Core MVC Select with dynamic searchig - javascript

I have a Login page, and I want to implement when an user type the username for example "Jh", because he is called Jhon, then next to the Login form there is a selectlist, and listing all the usernames from the database that contains Jh, and it should be dynamic, I mean if the input changes then update the search automatically.
Here is my view
<div class="row justify-content-center">
<div class="col-md-7">
<form asp-action="Login">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#if (!string.IsNullOrEmpty(ViewBag.Message))
{
<span class="text-danger">
#ViewBag.Message
</span>
}
#Html.HiddenFor(x => x.ReturnUrl)
<div class="form-group">
<label asp-for="UserId" class="control-label"></label>
<input asp-for="UserId" class="form-control" />
<span asp-validation-for="UserId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
#*<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="RememberLogin" /> #Html.DisplayNameFor(model => model.RememberLogin)
</label>
</div>
</div>*#
<div class="form-group">
<input type="submit" value="Bejelentkezés" class="btn btn-primary w-100" />
</div>
</form>
</div>
<div class="col-md-5">
<div class="form-group col-md-6">
<select asp-for="UserId" asp-items="ViewBag.Users" size="6" multiple class="form-control"></select>
<span asp-validation-for="UserId" class="text-danger"></span>
</div>
</div>
</div>
<script>
$("#search_id").keyup(function () {
//call ajax method
});
</script>
Here is my controller (Im using stored procedures):
public IActionResult Login(string ReturnUrl = "/")
{
LoginModel objLoginModel = new LoginModel();
objLoginModel.ReturnUrl = ReturnUrl;
string sqlQuery = "execute GetUsers";
var result = _context.GetUsers(sqlQuery);
ViewBag.Users = new SelectList(result, "UserId", "UserId");
return View("Login");
}

I write a simple demo here without any third part plugin, It is a basic demo to show how to achieve dynamic search, You can refer and make some changes to meet the needs of your own project. I hople it is what you want.
Model
public class Student
{
public string Id { get; set; }
public string Name { get; set; }
}
View
#model Student
<input asp-for="#Model.Name" oninput="Search(this.value)"/>
<div id="result"></div>
#section Scripts
{
<script>
function Search(data) {
var value ={
"name": data
}
$.post({
url: 'https://localhost:7209/Home/Download1',
ethod: 'Post',
data: value,
success: function (data) {
result = '';
for (var i = 0;i<data.length;i++){
result = result +'<tr><td>'+data[i].id+'</td><td>'+data[i].name+'</td></tr>';
}
document.getElementById("result").innerHTML = '<table class="table table-striped table-bordered zero-configuration dataTable" role="grid">'
+'<thead><tr><th>Id</th><th>Name</th></tr></thead>'
+'<tbody>'+result+'</tbody>'
+'</table>';
}
})
}
</script>
}
Home/Download1
[HttpPost]
public IActionResult Download1(string name)
{
//For testing convenience, I just hard code here, you can change it and select data from database
var result = Students.Where(x => x.Name.Contains(name)).ToList();
return Json(result);
}
Demo

Related

CKEDITOR textarea value is sent null to controller action in Asp.net Core MVC

I'm using CKEditor 4 and I'm going to post ckeditor value to Edit Action.
but when I click on submit button , ckeditor value is sent Null to the
controller edit action. I used getData() for get ckeditor value but it
didn't work.
This is Edit View:
#model DataLayer.Models.ViewModels.Post.ShowPostListItemViewModel
#{
ViewData["Title"] = "Post Edit";
}
<div class="row">
<form method="post" enctype="multipart/form-data">
<input type="hidden" asp-for="PostId" />
<div class="col-lg-12 col-md-12 col-sm-12">
<h1 class="page-header">Edit Post</h1>
</div>
<div class="row ">
<div class="col-md-8 col-sm-8 col-lg-8">
<div class="panel panel-primary">
<div class="panel-body col-md-12 col-sm-12">
<div class="form-group col-md-6 col-sm-6">
<label>Title</label>
<input type="text" asp-for="Title" class="form-control" />
<span class="text-danger" asp-validation-for="Title"></span>
</div>
<div class="form-group col-md-6 col-sm-6">
<label>Category</label>
<select type="text" asp-for="GroupId" asp-items="#(ViewData["Groups"] as SelectList)" class="form-control"></select>
</div>
<br />
<br />
<br />
<div class="form-group col-md-12 col-sm-12">
<label>PostDescription</label>
<textarea id="Post_PostDescription" class="form-control" asp-for="Description" rows="10"></textarea>
<span class="text-danger" asp-validation-for="Description"></span>
</div>
</div>
</div>
</div>
<br />
<br />
<div class="col-md-4 col-sm-4 col-lg-4">
<div class="panel panel-default ">
<div class="panel-body col-md-12 col-sm-12 col-lg-12">
<span class="border"></span>
#await Component.InvokeAsync("EditPostImageComponent",Model)
<div class="col-md-4">
<p></p>
<div class="form-group">
<label class="control-label">Select Image</label>
<input type="file" name="imgPostUp" id="imgPostUp" multiple="multiple">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 col-sm-11">
<p>
<input type="submit" asp-area="Admin" asp-controller="Post" asp-action="EditPost" value="Edit" class="btn btn-success" />
Back
</p>
</div>
</div>
</form>
</div>
#section Scripts
{
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgPost').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgPostUp").change(function () {
readURL(this);
});
</script>
<script src="https://cdn.ckeditor.com/4.9.2/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace('Post_PostDescription', {
customConfig: '/js/Config.js'
});
</script>
}
This is Edit action method in Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult EditPost(ShowPostListItemViewModel showPostListItemViewModel, IFormFile[] imgPostUp)
{
if (!ModelState.IsValid)
return View("EditPost");
_postService.UpdatePost(showPostListItemViewModel, imgPostUp);
return RedirectToAction("GetPost","Post");
}
This is ShowPostListItemViewModel:
public class ShowPostListItemViewModel
{
public int PostId { get; set; }
public int GroupId { get; set; }
public int PostImageId { get; set; }
public string Title { get; set; }
public string? GroupTitle { get; set; }
public string? ImageName { get; set; }
public string Description { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? UpdateDate { get; set; }
}
How can I post ckeditor value to controller action to edit?
thanks a lot...
ckeditor value is sent Null to the controller edit action
I test your code, and I can get the value, but even I don't have /js/Config.js, try to commentary Config.js, and try. Or check your Config.js to find the reason.
result:
Update
Below is a work demo(.Net 6) based on your code, you can refer to the follow steps to creat a new project or check your project.
ShowPostListItemViewModel is yours.
2.PostController:
[Area("Admin")]
public class PostController : Controller
{
public IActionResult EditPost()
{
//do your staff...
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult EditPost(ShowPostListItemViewModel showPostListItemViewModel, IFormFile[] imgPostUp)
{
//do your staff...
return View();
}
}
3.EditPost view:
I don't have the Component so I commentary #await Component.InvokeAsync("EditPostImageComponent",Model)
Then I change like yours:
<script> CKEDITOR.replace('Description'); </script>
4.In Program.cs add below route, you can read Areas in ASP.NET Core to know more:
app.MapControllerRoute(
name: "Admin",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
5.Copy the _ViewImports.cshtml file and _ViewStart.cshtml file to the appropriate view folder under areas.
The structure is like below:

Trying to dynamically insert javascript values into asp tag helper element

#page
#model Vescoverer.Pages.Registration.LocationModel
#{
ViewData["Title"] = "Location";
}
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div id="long" class="form-group">
<label asp-for="User.Longitude" class="control-label"></label>
<input id="long" asp-for="User.Longitude" class="form-control" />
<span asp-validation-for="User.Longitude" class="text-danger"></span>
</div>
<div id="lat"class="form-group">
<label asp-for="User.Latitude" class="control-label"></label>
<input asp-for="User.Latitude" class="form-control" v />
<span asp-validation-for="User.Latitude" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="User.Longitude" type="submit" value="Next" class="btn btn-primary" />
</div>
</form>
<button onclick="getLocation()">Get Location</button>
</div>
</div>
<script>
var lat = document.getElementById("lat");
var long = document.getElementById("long");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
lat.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
lat.innerHTML = position.coords.latitude;
long.innerHTML = position.coords.longitude;
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Location",
data: { //Passing data
Longitude: //insert data value, //Reading text box values using Jquery
Latitude: //insert data value
}
});
}
</script>
I want the longitude and latitude results to go into the appropriate form input values to be passed into the backend when the user clicks Get Location, instead the result replaces the form values with the innerHTML string. i know the asp-for tag heper handles the server side aspect but i'm not sure how to get the javascript results to be displayed in the form value. So when the user presses next, the data is passed into the database, as you can see i'm also trying to use Ajax but i'm not too sure.
You can use the ".val(value)" method to set the value of each element in the set of matched elements.
$("input[name*='Latitud']").val(position.coords.latitude);
$("input[name*='Longitude']").val(position.coords.longitude);
Result
The following is the complete demo, you can refer to it.
Model
public class User
{
public string Longitude { get; set; }
public string Latitude { get; set; }
}
xxx.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty]
public new User User { get; set; }
public void OnGet()
{
}
public void OnPost()
{
}
}
xxx.cshtml
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div id="long" class="form-group">
<label asp-for="User.Longitude" class="control-label"></label>
<input id="long" asp-for="User.Longitude" class="form-control" />
<span asp-validation-for="User.Longitude" class="text-danger"></span>
</div>
<div id="lat" class="form-group">
<label asp-for="User.Latitude" class="control-label"></label>
<input asp-for="User.Latitude" class="form-control" v />
<span asp-validation-for="User.Latitude" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Next" class="btn btn-primary" />
</div>
<button type="button" onclick="getLocation()">Get Location</button>
</form>
</div>
</div>
#section scripts{
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
lat.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
$("input[name*='Latitud']").val(position.coords.latitude);
$("input[name*='Longitude']").val(position.coords.longitude);
}
</script>
}

ASP.NET Core MVC update partial view after submitig a form

This is in ASP.NET Core MVC 2.1.
What I have is a main Index page on witch I load all my partial views.
<button type="button" id="CreateButton" class="btn btn-success" style="margin-top: 20px;">Nova osoba</button>
<button type="button" id="LoadDataButton" class="btn btn-info" style="margin-top: 20px;">Ucitati podatke</button>
<div id="CreateEditView">
</div>
<div id="TablePeopleView">
</div>
The way I load data into "TablePeopleView" is like this.
function AjaxCall(url) {
$("#TablePeople").replaceWith(
$.ajax({
url: url,
method: "POST",
success: function (html) {
$("#TablePeopleView").html(html);
}
}));
}
$(document).ready(function () {
AjaxCall("#Url.Action("IndexAjax")");
});
This calls the IndexAjax method from the controller and creates this partial view inside "TablePeopleView"
#model List<Person>
<table style="margin-top: 20px;" class="table table-condensed" id="TablePeople">
<thead>
<tr>
<th>ID</th>
<th>Ime</th>
<th>Prezime</th>
<th>Grad</th>
<th>Postanski broj</th>
<th>Broj mobitela</th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.ID</td>
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.CityName</td>
<td>#item.PostalCode</td>
<td>#item.MobileNumber</td>
<td>
<button type="button" class="btn btn-toolbar EditButton" data-url="#Url.Action("Edit","Zadatak")/#item.ID">
Uredi osobu
</button>
</td>
<td>
<button type="submit" class="btn btn-danger DeleteButton" data-url="#Url.Action("Delete","Zadatak")/#item.ID">
Obriši osobu
</button>
</td>
</tr>
}
</tbody>
</table>
And it works fine, gets the data and shows it on table.
When I want to create a new person I click on the "CreateButton" and get a new partial view inside "CreateEditView". The partial view looks like this.
#model Person
<div class="modal fade" id="CreateOrEditModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
#if (Model == null)
{
<h4 class="modal-title">Nova osoba</h4>
}
else
{
<h4 class="modal-title">Uredi osobu</h4>
}
</div>
<div class="modal-body">
<form asp-controller="Zadatak" id="CreateOrEditModalForm">
<div class="form-group">
<label class="control-label">Ime osobe</label>
<input asp-for="FirstName" class="form-control" id="FirstName" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Prezime osobe</label>
<input asp-for="LastName" class="form-control" id="LastName" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Naziv grada</label>
<input asp-for="CityName" class="form-control" id="CityName" />
<span asp-validation-for="CityName" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Poštanski broj</label>
<input asp-for="PostalCode" class="form-control" id="PostalCode" onkeypress="return isNumberKey(event)" />
<span asp-validation-for="PostalCode" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Mobilni broj</label>
<input asp-for="MobileNumber" class="form-control" id="MobileNumber" onkeypress="return isNumberKey(event)" />
<span asp-validation-for="MobileNumber" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Pospremi osobu" class="btn btn-default" id="SavePerson" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="ClosePerson" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
The way I get the partial view to show up in "CreateEditView" is like this.
$('#CreateButton').click(function () {
var url = "#Url.Action("Create","Zadatak")";
$("#CreateEditView").load(url, function () {
$("#CreateOrEditModal").modal("show");
});
});
The way I save date from the form "CreateOrEditModalForm" is with this.
$("#CreateEditView").on("click", "#SavePerson", function (event) {
$("#CreateOrEditModalForm").removeData('validator');
$("#CreateOrEditModalForm").removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse("#CreateOrEditModalForm");
$("#CreateOrEditModalForm").validate();
if ($("#CreateOrEditModalForm").valid()) {
$("#CreateOrEditModal").modal("hide");
}
});
I had to do it like this because it is loaded through a partial view witch is not loaded on page load.
After the form is validated it calls the "Create" method from the controller witch looks like this.
[HttpPost]
public IActionResult Create(Person model)
{
if (ModelState.IsValid)
{
this._dbContext.People.Add(model);
this._dbContext.SaveChanges();
return NoContent();
}
return NoContent();
}
Now this is where my problem comes I think. If the "ModelState.IsValid" is valid the new person will be saved to the DB and it will return NoContent. I put no content so the page does not refresh but if I put return RedirectToAction(nameof(IndexAjax)); like I did in the begginig it just loads the partila view in a new page like this.
I do not want that to happen, I just want the table to be refreshed with the new person while staying on the page.
Ajax allows websites to load content onto the screen without refreshing the page.
Here is a working demo you could check:
Model:
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string CityName { get; set; }
public string PostalCode { get; set; }
public string MobileNumber { get; set; }
}
View(Views/Zadatak/Index.cshtml):
<button type="button" id="CreateButton" class="btn btn-success" style="margin-top: 20px;">Nova osoba</button>
<button type="button" id="LoadDataButton" class="btn btn-info" style="margin-top: 20px;">Ucitati podatke</button>
<div id="CreateEditView">
</div>
<div id="TablePeopleView">
</div>
#section Scripts
{ //be sure add _ValidationScriptsPartial....
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
function AjaxCall(url) {
//the same as yours..
}
$(document).ready(function () {
AjaxCall("#Url.Action("IndexAjax")");
});
$('#CreateButton').click(function () {
//the same as yours..
});
$("#CreateEditView").on("click", "#SavePerson", function (event) {
$("#CreateOrEditModalForm").removeData('validator');
$("#CreateOrEditModalForm").removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse("#CreateOrEditModalForm");
$("#CreateOrEditModalForm").validate();
if ($("#CreateOrEditModalForm").valid()) {
$("#CreateOrEditModal").modal("hide");
//add the following code....
$("#TablePeople").replaceWith(
$.ajax({
url:"#Url.Action("Create", "Zadatak")",
method: "POST",
data: $("#CreateOrEditModalForm").serialize(),
success: function (html) {
$("#TablePeopleView").html(html);
}
}));
}
});
</script>
}
Be sure modify your CreateEditView.cshtml:
#model Person
<div class="modal fade" id="CreateOrEditModal" role="dialog">
//...
<div class="form-group">
#*change type="submit" to type="button"*#
<input type="button" value="Pospremi osobu" class="btn btn-default" id="SavePerson" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="ClosePerson" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
Controller:
public class ZadatakController : Controller
{
private readonly YourContext _context;
public ZadatakController(YourContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> IndexAjax()
{
//change here....
return PartialView("_IndexTable", await _context.Person.ToListAsync());
}
public IActionResult Create()
{
return PartialView("CreateEditView");
}
[HttpPost]
public async Task<IActionResult> Create(Person person)
{
if (ModelState.IsValid)
{
_context.Add(person);
await _context.SaveChangesAsync();
//change here....
return PartialView("_IndexTable", await _context.Person.ToListAsync());
}
return View(person);
}
}
Result:

Cascading Dropdown in Blazor

I'm using server side Blazor - I have my list of countries in the country table with two columns- CountryCode and CountryName. How do i dispaly the data using InputSelect to select a countryname and populate the countryCode
Here is my razor page:
<EditForm Model="#DisplayCountry" OnValidSubmit="#InsertCountry">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="col-12 row">
<label class="col-2 font-weight-bold">CountryCode:</label>
<InputSelect id="CountryCode" #bind-Value="DisplayCountry.CountryCode" />
<ValidationMessage For="#(() => DisplayCountry.CountryCode)" />
</div>
<div class="col-12 row">
<label class="col-2 font-weight-bold">CountryName:</label>
<InputText id="CountryName" #bind-Value="DisplayCountry.CountryName" placeholder="CountryName" />
<ValidationMessage For="#(() => DisplayCountry.CountryName)" />
</div>
<br />
<div class="col-12 row">
<span class="col-2"></span>
<input type="submit" class="form-control col-1 btn btn-primary" value="Save" />
</div>
Here is a simple demo like below:
Model:
namespace BlazorApp1.Models
{
public class Country
{
public string CountryCode { get; set; }
public string CountryName { get; set; }
}
}
Razor:
#page "/counter"
#using BlazorApp1.Models
#using BlazorApp1.Data
#inject CountryService countryService
<EditForm Model="#DisplayCountry">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="col-12 row">
<label class="col-2 font-weight-bold">CountryCode:</label>
<InputSelect #bind-Value="#coutryName" class="form-control">
#foreach (var cnt in DisplayCountry)
{
<option value="#cnt.CountryName">#cnt.CountryCode</option>
}
</InputSelect>
<ValidationMessage For="#(() => DisplayCountry[0].CountryCode)" />
</div>
<div class="col-12 row">
<label class="col-2 font-weight-bold">CountryName:</label>
<InputText id="CountryName" #bind-Value="#coutryName" placeholder="CountryName" class="form-control"/>
<ValidationMessage For="#(() => DisplayCountry[0].CountryName)" />
</div>
<br />
<div class="col-12 row">
<span class="col-2"></span>
<input type="submit" class="form-control col-1 btn btn-primary" value="Save" />
</div>
</EditForm>
#code
{
string coutryName;
List<Country> DisplayCountry = new List<Country>();
protected override void OnInitialized()
{
DisplayCountry = countryService.GetCountry();
}
}
Service:
namespace BlazorApp1.Data
{
public class CountryService
{
public List<Country> GetCountry()
{
//for easy testing,I just hard-coded assignment
//you could get the data from database like
//_context.Country.ToList()
var data = new List<Country>()
{
new Country() { CountryCode="1011", CountryName="USA"},
new Country() { CountryCode="1021", CountryName="Africa"},
new Country() { CountryCode="1031", CountryName="China"},
new Country() { CountryCode="1041", CountryName="UK"},
};
return data;
}
}
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
//register the service
services.AddSingleton<CountryService>();
}
Results:
If you do not want to get data from service,you could seed data like here.

Save Image in JSON for Rest

I am currently coding on a project for school, which should be a picture sharing website.
Spring Framework is handling the database as well as the rest interface. On the rest interface I have a RemoteImage, which represents an Image saved in the Database. I also have Getters, Setters and Cunstructors in there, but did not copied it in here.
#XmlRootElement
public class RemoteImage {
private Long id;
private String name;
private String contentType;
private byte[] content;
private Date createdAt;
private String owner;
private String camera;
private String lens;
private String aperture;
private String focalLength;
private String shutterSpeed;
private String ISO;
private String description;
private Long ownerId;
private Long categoryId;
....
In the Rest Resource I have the addImage function which converts the RemoteImage from the Rest into a Image for storing in the Database. The RemoteImage does not contain votes.
#POST
#Transactional
public void addImage(RemoteImage remoteImage) {
try {
Image image = new Image(
remoteImage.getName(),
remoteImage.getContentType(),
remoteImage.getContent(),
remoteImage.getCreatedAt(),
remoteImage.getOwner(),
remoteImage.getCamera(),
remoteImage.getLens(),
remoteImage.getAperture(),
remoteImage.getFocalLength(),
remoteImage.getFocalLength(),
remoteImage.getISO(),
remoteImage.getDescription(),
remoteImage.getOwnerId(),
remoteImage.getCategoryId()
);
service.save(image);
} catch (DataIntegrityViolationException e) {
sendError(409, "Image could not be stored. " + e.toString());
}
}
I tested this function with following Test:
#Test
public void testImageUpload() throws URISyntaxException, IOException {
login(james.getEmail(), "password");
RemoteImage image = createTestRemoteImage("test", james);
List<Image> images = r.path("image")
.header(AUTHENTICATION_HEADER, createAuthenticationHeader("kai#ima.at", "password"))
.accept(MediaType.APPLICATION_JSON)
.get(new GenericType<List<Image>>() {
});
assertThat(images.size(), is(0));
r.path("image").header(AUTHENTICATION_HEADER, createAuthenticationHeader("kai#ima.at", "password")).post(image);
List<Image> images1 = r.path("image")
.header(AUTHENTICATION_HEADER, createAuthenticationHeader("kai#ima.at", "password"))
.accept(MediaType.APPLICATION_JSON)
.get(new GenericType<List<Image>>() {
});
assertThat(images1.size(), is(1));
}
private RemoteImage createTestRemoteImage(String name, Customer customer) throws URISyntaxException, IOException {
byte[] bytes = FileUtils.readFileToByteArray(new File(getClass().getResource("/images/test.jpg").toURI()));
RemoteImage image = new RemoteImage(name, "image/jpeg", bytes, bytes, new Date(), customer.getEmail(), "Samsung NX300M", "Minolta MD 1.4", "1.4", "50", "2000", "200", "Test Image description", customer.getId(), 1L);
return image;
}
This seems to work fine so far, but in the Front End, in my case AngularJS, where I have a controller for adding an Image.
controllers.controller 'ImageAddController', ['$scope','$routeParams','$location','Image', ($scope, $routeParams, $location, Image) ->
$scope.image = {name:"",description:""}
$scope.error = null
$scope.add = ->
Image.save $scope.image,
(text,headers,context) ->
$scope.error = null
$location.path('/images/')
(request) ->
$scope.error = request.data
]
The matching view for that controller is the following
<div class="body-content">
<h1>Add Image</h1>
<div class="panel col-lg-8 col-offset-2">
<div class="panel-heading">
<h3 class="panel-title">New Image</h3>
</div>
<div class="alert alert-danger" data-ng-bind="error" data-ng-show="error"></div>
<form novalidate name="imageForm" class="css-form">
<fieldset>
<div class="form-group" >
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" id="name"
data-ng-model="image.name" required name="name"/>
</div>
<div class="form-group">
<label for="description" class="control-label">Description</label>
<input type="text" class="form-control" id="description"
data-ng-model="image.description" required name="description"/>
</div>
<div class="form-group">
<label for="category" class="control-label">Category</label>
<input type="text" class="form-control" id="category"
data-ng-model="image.categoryId" name="category"
required />
</div>
<div class="form-group">
<label for="camera" class="control-label">Camera</label>
<input type="text" class="form-control" id="camera"
data-ng-model="image.camera" name="camera"
required />
</div>
<div class="form-group">
<label for="lens" class="control-label">Lens</label>
<input type="text" class="form-control" id="lens"
data-ng-model="image.lens" name="lens"
required />
</div>
<div class="form-group">
<label for="aperture" class="control-label">Aperture</label>
<input type="text" class="form-control" id="aperture"
data-ng-model="image.aperture" name="aperture"
required />
</div>
<div class="form-group">
<label for="focalLength" class="control-label">Focal length</label>
<input type="number" class="form-control" id="focalLength"
data-ng-model="image.focalLength" name="focalLength"
required />
</div>
<div class="form-group">
<label for="shutterSpeed" class="control-label">Shutter speed</label>
<input type="text" class="form-control" id="shutterSpeed"
data-ng-model="image.shutterSpeed" name="shutterSpeed"
required />
</div>
<div class="form-group">
<label for="ISO" class="control-label">ISO</label>
<input type="number" class="form-control" id="ISO"
data-ng-model="image.ISO" name="ISO"
required />
</div>
</fieldset>
<div class="btn-toolbar">
<button class="btn btn-primary" data-ng-click="add()"
data-ng-disabled="customerForm.$invalid">Save</button>
Cancel
</div>
</form>
</div>
</div>
My question is how do let the user upload a picture to save it in the JSON (byte[] content) and how would I be able to display that image from an JSON for the user?
PS: The controller is not writen in Javascipt, it is Coffeescript. But because I guess more of you understand Javascript, you can help me in that language.

Categories

Resources