I want to use Bootstrap-select in Blazor Server app, i did all steps from Bootstrap-select website(https://developer.snapappointments.com/bootstrap-select/) to my blazor server app and also install bootstrap-select package from NuGet package manager but there is no effect to select element. Is it possible to use Bootstrap-select in blazor app. I will be very thankful if somebody help.
It is my razor Component:
#page "/"
<select class="selectpicker" data-live-search="true">
<option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
<option data-tokens="mustard">Burger, Shake and a Smile</option>
<option data-tokens="frosting">Sugar, Spice and all things nice</option>
</select>
You have used the library javascript files but are missing multiple dependencies: jQuery and bootstrap js files. bootstrap-select requires Bootstrap js and Bootstrap js requires jQuery and popper.js
You need to read this on how to fully add bootstrap js files. After that you can use any other Bootstrap based javascript library.
Preferably, you will also need to call the bootstrap-select init code after the page has rendered.
See the below javascript code:
window.InitSelectPicker = (dotnetHelper, callbackMethodName, pickerElementName) => {
// initialize the specified picker element
$(pickerElementName).selectpicker();
// setup event to push the selected dropdown value back to c# code
$(pickerElementName).on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
dotnetHelper.invokeMethodAsync(callbackMethodName, $(pickerElementName).val());
});
}
Note the changed.bs.select event being called. which will get the selected value.
See the razor file with c# code to init and callback selected value:
// inject jsruntime to call javascript code
[Inject] public IJSRuntime JSRuntime { get; set; }
// hold the callback selected value
public string SelectedValue { get; set; }
// call the javascript method to init the select picker
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) // only needs to be called once per page render
{
await JSRuntime.InvokeVoidAsync("InitSelectPicker", DotNetObjectReference.Create(this), "OnSelectedValue", ".selectpicker");
}
}
// method which will be triggered by javascript, need to pass the method name
[JSInvokable]
public void OnSelectedValue(string val)
{
SelectedValue = val;
StateHasChanged();
}
Complete source code here
Related
Ordinarily when using Blazored.Modal, a Modal dialog appears when I call IModalService.Show<> from a component, when IModalService is injected, which works great.
Should I expect a Modal dialog to appear when I call IModalService.Show<> from a method in a plain old C# class that is injected into a component (where IModalService is of course injected via the constructor)? The method is called from the component, of course.
I couldn't imagine why it wouldn't--after all, the runtime is injecting the same IModalService into both, right? But it does not and I don't understand why not. Do you?
using Blazored.Modal.Services;
namespace ...;
public class Class1 : IClass1
{
public Class1(IModalService modal)
{
Modal = modal ?? throw new ArgumentNullException(nameof(modal));
}
protected IModalService Modal { get; set; }
public void Show()
{
Modal.Show<MyDialog>();
}
}
Then, from the component:
#using Blazored.Modal.Services;
#inject IClass1 class1;
#inject IModalService modal;
<button #onclick="class1.Show" >Show it</button> #* doesn't work *#
<button #onclick="#() => modal.Show<MyDialog>()" >Show it</button> #* works *#
(Also asked here.)
I tried to replicate your scenario. When I tried to consume IModalService from a singleton service I got the following error:
Cannot consume scoped service 'Blazored.Modal.Services.IModalService'
from singleton 'BlazorWebAssembly.Client.Services.IMyModalService'.
After changing my service to scoped everything worked as expected and I was able to show modals.
In my Vaadin project, I have a component which extends AbstractJavaScriptComponent. I have added the javascript of the component using #JavaScript annotation.
#JavaScript({"app://./VAADIN/js/my-comp-connector.js"})
public class MyComp extends AbstractJavaScriptComponent {
}
Whenever I do a change to my-comp-connector.js, I need to clean browser cache so that browser re-downloads the changed javascript.
How can I force re-download of the javascript when I do a change to it?
I got it fixed by adding a query parameter to javascript path specified in #JavaScript annotation.
#JavaScript({"app://./VAADIN/js/my-comp-connector.js?v=2"})
public class MyComp extends AbstractJavaScriptComponent {
}
I'm writing an MVC 4 application using with AngularJS and Razor views. I want to pass the Web.config values to my AngularJS controller. How can I do that? Any idea?
If you have a razor template that is rendering your angular script elements, you can add to it an inline startup script like this:
Whatever.cshtml:
<script type="text/javascript">
angular.module('app')
.provider('appConfig', function appConfig () {
var values = {
SomeConfigValue: '#ConfigurationManager.AppSettings["Setting1"]'
};
return {
$get: function () {
return values;
}
};
});
</script>
And then inject 'appConfig' wherever you need it in your angular controllers/services/etc.
They are by nature inaccessible to client-side libraries (i.e. Javascript), if you wanted to write a mvc controller that exposed your web.config settings, that would be about your best option.
I am unable to find the attribute which holds the selected value in the case of <s:inputtransferselect/> Struts Tag. I referred to the documentation but I'm still unable to figure out which attribute exactly holds the selected values.
In the case of <s:optiontransferselect/>, I was able to get the selected values from the doubleId attribute. I am looking for a similar attribute for <s:inputtransferselect/>.
Inputtransferselect creates an input field, a multi option select list and some buttons to add and remove from the select list. When you submit your form this triggers some javascript to select all of the options in the select list, these options then appear in the list on the java side.
Here is an example.
Your .jsp file:
<s:inputtransferselect
key="cartoonCharacters"
addLabel="Add element"
removeLabel="Remove element"
removeAllLabel="Remove all elements"
upLabel="Move up"
downLabel="Move down"
leftTitle="Add Character"
rightTitle="Existing Characters"
list="cartoonCharacters"
/>
Make sure that your .jsp includes a <s:head/> tag else the javascript required for the inputtransferselect to work won't be available to your page.
To see all available attribute parameters of this tag refer to the documentation.
Your action .java file should contain a list which corisponds to the key and list of your inputtransferselect. To get hold of the values, use the list's getter:
public abstract class MyAction extends AbstractAction
{
private List<String> cartoonCharacters = new ArrayList<>();
public MyAction()
{
cartoonCharacters.add("Popeye");
cartoonCharacters.add("Superman");
cartoonCharacters.add("Scoobydoo");
}
public List<String> getCartoonCharacters()
{
return this.cartoonCharacters;
}
public void setCartoonCharacters(List pCartoonCharacters)
{
this.cartoonCharacters = pCartoonCharacters;
}
public String execute() throws Exception
{
return SUCCESS;
}
}
I should also note that in my implementation I haven't got this to work properly - the javascript to automatically select all options on form submit isn't firing so I had to write my own event for this, it's probably something to do with my other on submit events clashing.
When testing an ASP.NET MVC 2 application I hit a problem when a view could not be located.
Looking at the code I realised that the aspx file for the view had not been added to the source control repository. On this project that's quite easy to do as we use StarTeam for source control and it doesn't show new folders when checking in. This view was for a new controller and so a new folder was created for it and it was therefore missed.
Our build server (using Hudson/MSBuild) didn't pick up on this, as the code still builds fine with the aspx file missing. Our controller unit tests test the ActionResults which obviously still pass without the view there.
This got picked up in system testing but how can I catch this earlier (ideally on the build server).
Thanks in advance
You can write unit tests that test the actual view, and then if the unit test doesn't pass on the build server, you know you have a problem. To do this, you can use a framework such as this:
http://blog.stevensanderson.com/2009/06/11/integration-testing-your-aspnet-mvc-application/
With this you can write unit tests such as this (from the post)
[Test]
public void Root_Url_Renders_Index_View()
{
appHost.SimulateBrowsingSession(browsingSession => {
// Request the root URL
RequestResult result = browsingSession.ProcessRequest("/");
// You can make assertions about the ActionResult...
var viewResult = (ViewResult) result.ActionExecutedContext.Result;
Assert.AreEqual("Index", viewResult.ViewName);
Assert.AreEqual("Welcome to ASP.NET MVC!", viewResult.ViewData["Message"]);
// ... or you can make assertions about the rendered HTML
Assert.IsTrue(result.ResponseText.Contains("<!DOCTYPE html"));
});
}
What version of StarTeam are you running? In StarTeam 2008 (not sure when this feature was first added) within a selected project/view, you can select from the menu Folder Tree->Show Not-In-View Folders. This will show folders you have on local disk that have not been added to the project (they will appear with the folder icon colored white).
This is an old question, but if anyone still looking for this you ought to try SpecsFor.Mvc by Matt Honeycutt.
Not only it can be used to make sure the Views are properly included/added in the source control, it can even do integration test to make sure those Views are valid.
Link to its website: http://specsfor.com/SpecsForMvc/default.cshtml
Link to the nuget package: https://www.nuget.org/packages/SpecsFor.Mvc/
Link to github: https://github.com/MattHoneycutt/SpecsFor
Here is a code snippet taken from the website showing how to use it.
public class UserRegistrationSpecs
{
public class when_a_new_user_registers : SpecsFor<MvcWebApp>
{
protected override void Given()
{
SUT.NavigateTo<AccountController>(c => c.Register());
}
protected override void When()
{
SUT.FindFormFor<RegisterModel>()
.Field(m => m.Email).SetValueTo("test#user.com")
.Field(m => m.UserName).SetValueTo("Test User")
.Field(m => m.Password).SetValueTo("P#ssword!")
.Field(m => m.ConfirmPassword).SetValueTo("P#ssword!")
.Submit();
}
[Test]
public void then_it_redirects_to_the_home_page()
{
SUT.Route.ShouldMapTo<HomeController>(c => c.Index());
}
[Test]
public void then_it_sends_the_user_an_email()
{
SUT.Mailbox().MailMessages.Count().ShouldEqual(1);
}
[Test]
public void then_it_sends_to_the_right_address()
{
SUT.Mailbox().MailMessages[0].To[0].Address.ShouldEqual("test#user.com");
}
[Test]
public void then_it_comes_from_the_expected_address()
{
SUT.Mailbox().MailMessages[0].From.Address.ShouldEqual("registration#specsfor.com");
}
}
}