I am trying to display some data fetched from database into a Textarea of my Razor page.
I have tried out something like this. Is this the correct way of displaying the data for view only?
Razor page code snippet:
#if(summaryProjection != null)
{
<div> Seller Data</div>
<textarea>
#summaryProjection.tradeSummary.articleCurrency
</textarea>
}
cs side code:
public Models.SummaryProjection summaryProjection = new Models.SummaryProjection();
protected override async Task OnInitializedAsync()
{
string Id = TID;
summaryProjection = await Http.GetFromJsonAsync<Models.SummaryProjection>($"api/T/summary?Id=" + Id);
}
If it's a block of text you want to display then textarea is as good a solution as any other (with some css formatting to make it pretty). You will need to add disabled to prevent editing. In your example you appear to want to display a currency value. for that it's not the best - just use a suitably styled input, again with disabled set.
<textarea disabled>
#summaryProjection.tradeSummary.articleCurrency
</textarea>
Related
I am running into an odd issue using Blazor Webassembly. I have a component that has 2 text boxes. For some reason, if I type anything into the first text box, then try to either tab to the second text box or click in the second text box, I have to do it twice. It's like the first tab or click doesn't register. After playing around with it, I was able to minimally duplicate the issue. The issue seems to happen when I have both a model binding on the control and I use a #ref attribute.
Here is my .cshtml file:
#inject IJSRuntime JsRuntime
#page "/"
<div>
<input class="form-control" id="first-text-box" type="text" #ref="TextBoxControl" #bind="_model.Box1" />
</div>
<div>
<input class="form-control" id="second-text-box" type="text" #bind="_model.Box2" />
</div>
#code {
private ElementReference TextBoxControl { get; set; }
private readonly BoxClass _model = new BoxClass();
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await JsRuntime.InvokeVoidAsync("jsFunctions.focusElement", TextBoxControl);
await base.OnAfterRenderAsync(firstRender);
}
}
Here is the focusElement javascript function:
window.jsFunctions = {
focusElement: function(element) {
element.focus();
}
};
Finally, here is a Fiddle of the issue to see it happen live: https://blazorfiddle.com/s/kph6msiv
Like I said, just type something into the first text box, then try to tab or click to the next text box and you'll see that you'll need to do it twice.
You are focusing every time it renders, which happens when Blazor data binds, which happens when you exit the control.
Instead, only call your JavsScript if firstRender is true
I would like to load a list of students at moment I have a signalr connection and the request gets all students. I'd like to scroll down the list and it would load a 100 students at a time?
<ul>
#if (Students != null)
{
#foreach (var student in Students)
{
<li>
<div class="treeview__item__header">
#plan.Name
</div>
</li>
}
}
</ul>
#code
{
private List<StudentsData> Students { get; set; }
protected override async Task OnInitializedAsync()
{
Students = await StudentsConnection.GetStudents();
}
}
I have used this example with success:
https://github.com/amuste/DnetVirtualScrolling
in alternative, as Alexander stated, a simple pager calculated on the number of rows to show and seems to be the best "pure blazor" solution
Edit: Looks like Virtualize could be perfect for this use:
https://www.syncfusion.com/blogs/post/asp-net-core-blazor-component-virtualization-in-net-5.aspx
I believe that you should consider solution on store procedure level with
Select top 100 where and have a parameter #next
With witch you could control from app with button or event when you scroll down to the end of list
you can use pagination and implement a pager component. Look at these two articles, they may help you: Pager component and part of Pager component 2
I'm currently working on an asp.net web form that uses Knockout, Bootstrap, and JQuery. I'm having an issue with data persistence through "Wizard steps."
What I would like to do is take in the mailing state of the client and persist it through to other pages, from there use Knockout to make fields visible and also create validation.
I've read that you can use hidden states to accomplish this but I've had issues getting the value to pass to Knockout and ultimately getting the other fields to show.
Here is the c# that does all the steps page to page.
protected void StepChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
if (QuoteWizard.ActiveStepIndex == 0)
txtFirstName.Focus();
if (QuoteWizard.ActiveStepIndex == 1)
{
Session["State"] = ddlState.Value;
rblMailAddr.Focus();
}
if (QuoteWizard.ActiveStepIndex == 3)
{
txtDriverFName1.Value = txtFirstName.Value;
txtDriverMI1.Value = txtMI.Value;
txtDriverLName1.Value = txtLastName.Value;
String DOB;
DOB = Convert.ToDateTime(txtDOB.Value).ToString();
txtDriverDOB1.Value = DOB;
txtDriverFName1.Focus();
}
I find it odd that the txtDriverFName1.Value = txtFirstNAme.Value; passes properly but I can't get the state from a drop down list or the date of birth to pass from one step to the other.
<select id="ddlState" runat="server" class="form-control" data-bind="value: MailState, updateValue: 'afterkeydown'">
Followed by the list of states, then I try to pass it to knockout to make fields visible:
self.MailState = ko.observable("", { persist: "MailState" });
However, once I reach the next step the values in the ViewState are dropped and
<div class="btn-group" data-toggle="buttons" style="padding-left: 10px" data-bind="visible: MailState() == 'CA'">
no longer becomes visible even when CA is selected in the previous viewstate.
So how would I persist the value of my drop down list through 2 or more steps in the QuoteWizard.ActiveStepIndex and have that assigned to "MailState()" subsequently activating Knockout?
in data-bind the bindinghandler handle to excute expression, then visible bindinghandler will unwrap it to value from observable. But in your code you use
data-bind="visible: MailState == 'CA'" //MailState is observalbe then like function() == 'CA' - that not right
should change to:
data-bind="visible: MailState() == 'CA'"
I need to create a webform where users can add, update, delete, retrieve customer data from a table in an SQL database.
Should have textboxes for each field in the table so that the users can enter details of the fields to update the table in the DB.
What im having trouble with is in the code behind the form i need to make a clear method to clear all the textboxes and the message label.
I also need to set validation requirements for each textbox. But i am unsure how to do this properly.
The textboxes are;
CustID, Firstname, Surname, Gender, Age, Address1, Address2, City, Phone, Mobile, Email, Confirm Email.
Now my main question is, how do i validate the textboxes? For example;
CustID is required. & Must be unique. Must be an integer and must be between 1 & 1000.
You should use RequiredValidator for example
http://www.w3schools.com/aspnet/control_reqfieldvalidator.asp
This will perform validation before submitting data to server ;)
There are also other type of validator, like RangeValidator (for the need to check if the integer is between 1 and 1000).
Example:
<asp:RangeValidator ControlToValidate="youtField" MinimumValue="1" MaximumValue="1000" Type="Integer" Text="The field must be between 1 and 1000" runat="server" />
You can also add a ValidationGroup="save" for example to all your validators and to the button that user should click to save and update data.
Asp.net Have some (5 main types) server validation control's , You can use the validations for your requirement
See this image for understanding validation controls (The image referred from )
More understanding by this MSDN sit3
and here is link for all validation control sample's : click me
Here could be an example for ASP/ MVC - because you have forgotten to specify which technology from ASP. Forms or MVC ?!?
This bellow aplies to mvc and the other attributes are allready defined by the users before me.
Note that the RemoteAttribute can verify a function (validation function) .
namespace ModelValidation.Models {
public class Appointment {
[Required]
[StringLength(10, MinimumLength = 3)]
public string ClientName { get; set; }
[DataType(DataType.Date)]
[Remote("ValidateDate", "Home")]
public DateTime Date { get; set; }
public bool TermsAccepted { get; set; }
}
}
To apply validation on a model property that describes a TextBox, then a good proactice is to use TextBoxFor<>(). Like that:
#Html.TextBoxFor((model) => model.ClientName )
You can clear all your controls values by either redirecting to user to another page telling him that form is submitted, New Registration button to redirect user again to Registration page, However if you don't want that you can pick up each control and reset them either in Cs.file or using javascript,
foreach (Control ctrl in form1.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.Text = string.Empty;
}
else if (ctrl is DropDownList)
{
DropDownList dl = (DropDownList)ctrl;
dl.SelectedIndex = 0;
}
else if (ctrl is CheckBox)
{
CheckBox cb = (CheckBox)ctrl;
cb.Checked = false;
}
}
For your validation purpose i strongly suggest you to read about validation in Asp.net , here is a good tutorial you can learn from here
To clear all textbox you can try something like this
foreach (var item in Page.Controls)
{
if (item is TextBox)
{
((TextBox)item).Text = "";
}
if (item is DropDownList)
{
((DropDownList)item).SelectedIndex= 0;
}
//and the other types
}
For the part of validation you have to set the validation fields that you desire and bind it to the field directly on the .aspx page
<asp:textbox ID="Name" runat="server" TabIndex="1"/>
<asp:RequiredFieldValidator ID="rfvName" ControlToValidate="Name" runat="server" ErrorMessage="Name is required">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
When you try to save and one of the condition of your validators returns false, the validation summary will show all the errors written in the errormessage attribute.
I'm pretty much a jquery newb...I've almost got this working I think, let me know if i can clarify anything.
I have a screen displaying a list..let's call them affiliates. To create a new affiliate, a modal style pop up dialogue is used.
When the dialogue "Create" button is clicked, the form data must be saved (creating a new affiliate), the dialogue disappears, and the affiliate list updates without reloading the page
The jquery file at the bottom shows how I'm trying to do it now: trying to detect a click on the "confirm" button, get the form to submit using the data target property, and using the form's target property to know what container to update.
What is happening is: nothing. The cancel button works, create button does absolutely nothing.
Also note that the "Create" button, which will act as the form's submit, is not located within the <form> tags.
I'm pretty sure I'm doing modals wrong but let's ignore that for the moment and focus on the async post and list update. I've included my relevant code below to support my post.
--AffiliateListPartial
#model IPagedList<Acme.Business.DomainModel.Affiliates.Affiliate>
<div class="items-list" id="affiliate-list-view">
#foreach (var item in Model)
{
<a href="#Url.Action("AffiliateDetails", "Vendor", new { id = item.AffiliateId })">
//basic spans and razor display list in here..nothing notable
</a>
}
</div>
The above partial view is contained within a full view, lets call it AffiliateList. Nothing particularly relevant in there except that it is controlled by the VendorController/Affiliatelist method.
The VendorController.AffiliateList looks like:
public ActionResult AffiliateList(string searchTerm = null, int page = 1)
{
var userId = WebSecurity.GetUserId(User.Identity.Name);
var model = (from a in db.Affiliates.ToList()
where a.VendorId == userId
select a).ToPagedList(page, 15);
if(Request.IsAjaxRequest()) return PartialView("_AffiliateListPartial", model);
return View(model);
}
The modal style dialoque for creating a new affiliate (I'll just include the lines that I think are relevant):
_Modal.AffiliateCreate.Partial
<form id="affiliate-create-form" class="form" method="post" action="#Url.Action("AffiliateCreate")" data-acme-ajax="true" data-acme-target="#affiliate-list-view">
// multiple input elements
</form>
<div class="modal-footer">
<button name="close_modal"><span>Cancel</span></button>
<button name="confirm" data-acme-target="#affiliate-create-form"><span>Create</span></button>
</div>
And the VendorController.AffiliateCreate method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AffiliateCreate(Affiliate affiliate)
{
if (!ModelState.IsValid) return View(affiliate);
db.Affiliates.Add(affiliate);
db.SaveChanges();
return RedirectToAction("AffiliateList");
}
And the .js file's relevant parts:
$("button[name='confirm']").on("click", function() {
var $form = $(this).attr("data-acme-target");
var options = {
url: $form.attr("action"),
type: $form.attr("type"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-acme-target"));
var $newHtml = $(data);
$target.replaceWith(data);
$newHtml.effect("highlight");
});
$(".modal_overlay").css("opacity", "0");
$(".modal_container").css("display", "none");
return false;
});
$("button[name='close_modal']").on("click", function(event) {
$(".modal_overlay").css("opacity", "0");
$(".modal_container").css("display", "none");
return false;
});
var $form = $(this).attr("data-acme-target"); is getting the attribute named 'data-acme-target' of the button, rather than the form it's associated with. So then when you're using $form.attr('action'), you aren't getting anything back.
Since data-acme-target is an ID to another control that is the form you want to submit, use $($(this).attr("data-acme-target")); to get it.