Asp.NET MVC Razor DropDownList and document with table part - entity-framework

I need to make a drop-down list box, which selects data from the related table.
I've used an example from MSDN, but it doesn't work.
public ActionResult Create()
{
TypeItemsDropDownList();
return View(new Item());
}
//
// POST: /Item/Create
[HttpPost]
public ActionResult Create([Bind(Include = "idItem,nameItem,priceItem,quantity,inStock,descrItem,idTypeItem")]Item item)
{
try
{
if (ModelState.IsValid)
{
iac.StoreNewItem(item);
return RedirectToAction("Index");
}
}
catch (System.Data.DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
TypeItemsDropDownList(item.idTypeItem);
return View(item);
}
private void TypeItemsDropDownList(object selectedTypeItem = null)
{
cabproddbEntities db = new cabproddbEntities();
var typeQuery = from d in db.TypeItem
orderby d.nameTypeItem
select d;
ViewBag.idTypeItem = new SelectList(typeQuery, "idTypeItem", "nameTypeItem", selectedTypeItem);
}
The error occurs here:
<div class="editor-label">
<label class="control-label col-md-2" for="idTypeItem">Тип продукции</label>
</div>
<div class="editor-field">
#Html.DropDownList("idTypeItem", String.Empty)
#Html.ValidationMessageFor(model => model.idTypeItem)
</div>
on this line: #Html.DropDownList("idTypeItem", String.Empty)
The table TypeItem has the data.
The thrown exception is: System.Data.EntityCommandExecutionException with the following details:
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.

Your issue is you are not linking your SelectList to the drop down. Use the DropDownListFor() helper and reference your select list in it. As shown below.
Your naming conventions are a little off also and this might be leading you into confusion.
#Html.DropDownListFor(m => Model.selectedItem, ViewBag.idTypeItem)

Related

Not able to get desired output for the following code

outputimage
.JS file
import { LightningElement, wire } from 'lwc';
import getContactList from '#salesforce/apex/ContactController.getContactList';
export default class ApexWireMethodToFunction extends LightningElement {
contacts;
error;
#wire(getContactList)
wiredContacts({ error, data }) {
if (data) {
this.contacts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.contacts = undefined;
}
}
}
HTML file:
<template>
<lightning-card
title="ApexWireMethodToFunction"
icon-name="custom:custom63"
>
<div class="slds-var-m-around_medium">
<template if:true={contacts}>
<template for:each={contacts} for:item="contact">
<p key={contact.Id}>{contact.Name}</p>
</template>
</template>
<template if:true={error}>
<c-error-panel errors={error}></c-error-panel>
</template>
</div>
<c-view-source source="lwc/apexWireMethodToFunction" slot="footer">
Call an Apex method that retrieves a list of records using #wire. In
this recipe, the Apex method is #wired to a component function.
</c-view-source>
</lightning-card>
</template>
APEX CLASS- CONTACTCONTROLLER
#AuraEnabled(cacheable=true)
public static List<Contact> getContactList() {
return [
SELECT
Id,
Name,
FirstName,
LastName,
MailingAddress
FROM Contact
WHERE Name != NULL
WITH SECURITY_ENFORCED
LIMIT 10
];
}
}
This is actually a code copy pasted from GitHub: 'LWC Recipes'--apexWireMethodToFunction LWC component.
But in HTML file, I have made small change. I have removed the line which has the reference for error-panel component and rest of the code is the same.
When I tried to deploy this code in my system I am getting the attached image as output. I am not sure as to why am I getting output as some undefined data.
Please help.
My best bet would be your user profile doesn't have access to the apex class. Thus the component is displaying the error part. As we don't see the error component code, it's hard to help you more.
You could use the browser devtool, go to network tab and search for your apex method call and see what is the raw answer from the server.

Can not get url with query string when changing culture

Culture info is not get query string when I change a language from English to German.
Startup.cs
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("de-DE"),
new CultureInfo("en-US"),
};
options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new QueryStringRequestCultureProvider(),
new CookieRequestCultureProvider()
};
});
It works properly when there is no query string in url. But I want to return that particular url with full query string. I wrote a method to set culture like this:
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
_Layout.cshtml
<form id="selectLanguage" asp-controller="Home"
asp-action="SetLanguage" asp-route-returnUrl="#returnUrl"
method="post" class="form-horizontal" role="form">
<select name="culture" onchange="this.form.submit();"
asp-for="#requestCulture.RequestCulture.UICulture.Name"
asp-items="cultureItems">
</select>
</form>
When I'm changing the lang, then it creates a url as shown here:
How can I get full query string like this:
Try change your returnUrl like below :
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value+Context.Request.QueryString.Value}";
I would suggest following solution since the accepted does not work when you're url contains a pathbase (which is the case for example when you host your service in IIS in with a virtual path):
returnUrl = UriHelper.BuildRelative(Context.Request.PathBase, Context.Request.Path, Context.Request.QueryString)

My controller won't recieve the input from the user (Spring boot)

My controller won't work - like adding the data into my DB.
public class BukuController {
#Autowired
private BukuService bukuservice;
#PostMapping(value = "/createBuku", method = RequestMethod.POST)
public String createBook(#RequestParam("judul") String judul, #RequestParam("tahun") int tahun, #RequestParam("penulis") String penulis) {
System.out.println("Judul : " + judul);
System.out.println("Tahun : " + tahun);
System.out.println("Penulis : " + penulis);
try {
bukuservice.getCreate(judul, penulis, tahun);
System.out.println("Berhasil");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("Gagal");
}
//
return "detail";
}
}
detail.html (Edited 3:48 PM because someone comment need file html i use for insert the data)
<body>
<form action="/buku/createBuku" method="post">Form Detail Buku<br><br>
Judul Buku : <input type="text" name="judul"><br>
Tahun : <input type="text" name="tahun"><br>
Nama Penulis : <input type="text" name="penulis"><br>
<input type="submit" value = "Submit">
</form>
I am new using thymeleaf. Can you give give some advice? Maybe I'm using the wrong dependencies or I am wrong on other java files like the model or service.
It's failing to save the input to the table and no warnings or errors pop up, it's running smoothly.

Update on 2 or more tables

I have a problem with the following piece of code, actually I have the following method:
#Transactional
def update(Subsidiary subsidiary,User user) {
if (subsidiary == null) {
transactionStatus.setRollbackOnly()
notFound()
return
}
if (subsidiary.hasErrors()) {
transactionStatus.setRollbackOnly()
respond subsidiary.errors, view:'edit'
return
}
user.save flush:true
user.addToSubsidiaries(subsidiary)
user.save flush:true
subsidiary.addToPhones(phone)
subsidiary.save flush:true
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.updated.message', args: [message(code: 'subsidiary.label', default: 'Subsidiary'), subsidiary.id])
redirect subsidiary
}
'*'{ respond subsidiary, [status: OK] }
}
}
Actually from the view in gsp
<g:form resource="${this.subsidiary}" class="form-horizontal" method="PUT">
<f:input bean="user" class="form-control" property="name"/>
<f:input bean="subsidiary" class="form-control" property="dob"/>
</g:form>
and these is the way I send the info the method unfortunately it loads everything properly but I get no changes the update does not work, the database is postgres and I already did a method similar but it only update one table and I also used the same sentences to create one subsidiary with success, however in the part of update it does not work it does nothing, I'm doing something wrong?

Umbraco cannot find the route in backoffice

I've used Umbraco 7.3 in my project. I created a custom data type but when I want to call a Surfacecontroller in here is HelloSurfaceController or Hello2SurfaceController, I got an error in umbraco backoffice that said Request error: The URL returned a 404 (not found):
I studied some articles about routing but I couldn't solve my problem. I don't know that where I did wrong.
How can I solve this problem?
Reply.controller.js:
angular.module("umbraco")
.controller("Reply.controller", function ($scope, $http) {
$scope.SendReply = function () {
var sendTo = $("#Email").val();
var textMessage = $("#TextMessage").val();
$scope.xxx = "I'm here!";
var data = { SendTo: sendTo, TextMessage: textMessage };
// ~/Hello2Surface/ReplyMessage ---> Cannot find this URL
$http.post("~/App_Plugins/Reply/HelloSurface/ReplyMessage") // Can not find this URL
.then(function (response) {
alert("YES!");
//TODO:
});
}
});
SurfaceController
namespace Jahan.Nuts.Web.Mvc.UmbracoCms.App.App_Plugins.Reply
{
public class HelloSurfaceController : SurfaceController
{
[HttpPost][ChildActionOnly]
public ActionResult ReplyMessage()
{
//TODO: how should be write this method that be proper for getting data from angularjs?
return null;
}
}
}
package.manifest
{
propertyEditors: [
{
alias: "Send.Reply",
name: "Send Reply",
editor:{
view:"~/App_Plugins/Reply/Reply.html"
},
}
]
,
javascript:[
'~/App_Plugins/Reply/Reply.controller.js'
]
}
Reply.html
<div ng-controller="Reply.controller">
<div style="width: 100%;">
<input type="button" value="Send Reply" title="SendReply" name="Send Reply" ng-click="SendReply()" />
</div>
<div>
<input type="text" ng-model="xxx" name="message" />
</div>
Error in umbraco backoffice:
Take a closer look at the documentation - in particular the Plugin-based SurfaceControllers section:
https://our.umbraco.org/documentation/Reference/Routing/surface-controllers
try doing this (note the PluginController attribute):
namespace Jahan.Nuts.Web.Mvc.UmbracoCms.App.App_Plugins.Reply
{
[PluginController("Reply")]
public class HelloSurfaceController : SurfaceController
{
[HttpPost][ChildActionOnly]
public ActionResult ReplyMessage()
{
//TODO: how should be write this method that be proper for getting data from angularjs?
return null;
}
}
}
Other Notes:
You don't need to include "Surface" in the controller name anymore - simply calling it HelloController is enough.
Don't use a SurfaceController for Api calls if you're using it with AngularJS - Better to use an UmbracoApiController instead. Check out https://our.umbraco.org/documentation/Reference/Routing/WebApi/ for more information (including notes on where to expect the Api Endpoint to be)
You might also want to re-locate your controller so it's in a more conventional spot. There's no problem with putting it in the ~/Controllers directory even if it is a Plugin Controller.
Edit: Added "correct" way to do this:
As noted above, to implement an UmbracoApiController, you want a class looking like this - note you can use UmbracoApiController if you don't need to worry about authorization:
namespace Jahan.Nuts.Web.Mvc.UmbracoCms.App.App_Plugins.Reply
{
[PluginController("Reply")]
public class HelloApiController : UmbracoAuthorizedApiController
{
public void PostReplyMessage(string to, string message)
{
// TODO: process your message and then return something (if you want to).
}
}
}
Then in AngularJS set up a resource like this:
function replyResource($q, $http, umbDataFormatter, umbRequestHelper) {
var replyResource = {
sendMessage: function (sendTo, msg) {
return umbRequestHelper.resourcePromise(
$http.post("Backoffice/Reply/HelloApi/PostReplyMessage?" +
umbRequestHelper.dictionaryToQueryString(
[{ to: sendTo }, { message: msg }])),
'Failed to send message to ' + sendTo + ': ' + msg);
}
};
return replyResource;
}
angular.module('umbraco.resources').factory('replyResource', replyResource);
and finally your actual view controller can use this as follows:
angular.module("umbraco")
.controller("Reply.controller", function ($scope, $http, $injector) {
// Get a reference to our resource - this is why we need the $injector specified above
replyResource = $injector.get('replyResource');
$scope.SendReply = function () {
// You really shouldn't use jQuery here - learn to use AngularJS Bindings instead and bind your model properly.
var sendTo = $("#Email").val();
var textMessage = $("#TextMessage").val();
replyResource.sendMessage(sendTo, textMessage)
.then(function (response) {
// Success
}, function (err) {
// Failure
});
}
};
});
It's possible there's some errors in there; I did it mostly from memory - in particular, you may need to look into the best way to post data to the ApiController - it's not likely that it'll just accept the two parameters like that.
For a more complete example, consider reviewing the code of the Umbraco MemberListView plugin: https://github.com/robertjf/umbMemberListView
Also, you really should read up on the ASP.Net MVC fundamentals and the Umbraco Documentation for SurfaceControllers and APIControllers I've listed above already.
remove the "Surface" from the URL and include "backoffice":
angular.module("umbraco")
.controller("Reply.controller", function ($scope, $http) {
$scope.SendReply = function () {
var sendTo = $("#Email").val();
var textMessage = $("#TextMessage").val();
$scope.xxx = "I'm here!";
var data = { SendTo: sendTo, TextMessage: textMessage };
// ~/Hello2Surface/ReplyMessage ---> Cannot find this URL
$http.post("backoffice/Reply/Hello/ReplyMessage") // Can not find this URL
.then(function (response) {
alert("YES!");
//TODO:
});
}
});
Also, I'd recommend using UmbracoAuthorizedController not a surface controller as this is being used in the back end by logged in users it'll be wise to keep it secure.
So instead your controller should look something like this:
[PluginController("Reply")]
namespace Jahan.Nuts.Web.Mvc.UmbracoCms.App.App_Plugins.Reply
{
public class HelloApiController : UmbracoAuthorizedJsonController
{
public [Model-to-be-returned-to-angular] ReplyMessage()
{
//sql query etc to populate model
//return model
}
}
}