Blazor: binding collection of elements to a List - data-binding

In my Blazor server-side application, I dynamically created multiple InputNumber controls based on the NumberOfOutlets provided by the user:
<div class="form-group row">
<label for="numberOfOutlets" class="col-form-label form-control-label col-sm-2">Number of Outlets</label>
<div class="col-sm-10">
<InputNumber id="numberOfOutlets" #bind-Value="QuoteModel.NumberOfOutlets" ParsingErrorMessage="Number of Outlets must be a valid number" class="form-control mx-2" />
</div>
</div>
#for (short outlet = 1; outlet <= QuoteModel.NumberOfOutlets; outlet++)
{
<div class="form-group row">
<label for="#($"outlet{outlet}offTheRight")" class="col-form-label form-control-label col-sm-2">Number of Outlets</label>
<div class="col-sm-10">
<InputNumber id="#($"outlet{outlet}offTheRight")" ParsingErrorMessage="Outlet location must be a valid number" class="form-control mx-2" />
</div>
</div>
}
How can I bind the InputNumbers to the following property?
public List<short> OutletLocations { get; set; } = new List<short>(50);
I don't need to populate the controls from the List, rather, I want to populate the List based on the values entered by the user.

Related

How to pass a js variable to the controller in ASP.NET Core

I am sending an id in my js code and I want to pass that variable to my controller. Any advice on how I can do that?
<input class="btn_confirm" type="submit" id={i}
onclick="id_click(this.id)" value="Delete" />
var id;
function id_click(clicked_id) {
id = clicked_id;
}
I tried different things but nothing worked out.
I tried as below:
Model:
public class ReceiveModel
{
public int Id { get; set; }
public string Name { get; set; }
public string SomeKey { get; set; }
}
View:
<div class="row">
<div class="col-md-4">
<form id="form" asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input id="1" type="submit" value="Create" class="btn btn-primary" />
</div>
<div class="form-group">
<input id="2" type="submit" value="Create" class="btn btn-primary" />
</div>
<div class="form-group">
<input id="3" type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$("input[type='submit']").click(function ()
{
var tempid = this.id
var tmpInput = $("<input type='text' name='SomeKey' hidden/>");
tmpInput.attr("value", tempid );
var form = $("#form")
form.append(tmpInput)
form.submit()
})
</script>
Result:
You can lookup API requests. If you want to send one parameter as a primitive type (string, integer, etc.) you can use query strings in your API calls. For example, let's assume you have an API endpoint like this: localhost:5000/api/YourController. You can send params via API get calls like this localhost:5000/api/YourController?yourParam=<param-value>. In this example your API call type is GET.
If you want to send complex types (like classes, objects) to your controller you can lookup POST API requests.
You can find more details in this documentation.

After the Mail is sent the message is showing Error: Your Query is sent successfull

Need help on issue related to Asp.Net Core MVC in the below screenshot as i sumbit the query the view is returned but the title of the msg "Error" is coming as i want to only render only success message, Thanks...
Please refer the screenshot attached to have more clearity on issue
Below is my form code
<form action="/ContactUs/ContactSubmitQuery" method="post" role="form" class="php-email-form" asp-antiforgery="true">
#Html.AntiForgeryToken()
<div class="form-row">
<div class="col-lg-6 sm-6 form-group">
<label>Name</label>
<input type="text" name="cname" class="form-control input-css click-cg textbox" id="cname" placeholder="Name"
data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-lg-6 sm-6 form-group">
<label>Email</label>
<input type="email" class="form-control input-css click-cg textbox" name="email" id="email" placeholder="Email"
data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control click-cg textbox" name="description" rows="5" data-rule="required"
data-msg="Please write something for us" placeholder="Description"></textarea>
<div class="validate"></div>
</div><br>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit">Send</button></div>
</form>
and below is my controller code where am using OK to return success message once the email is sent
public IActionResult ContactSubmitQuery()
{
string name = Request.Form["cname"];
string email = Request.Form["email"];
string message = Request.Form["description"];
string htmlContent = string.Format("name:{0} <br/> email:{1} <br/> message:{2}", name, email, message);
SendEmail send = new SendEmail("Test Contact", EmailType.Single);
send.Send(htmlContent);
//return Ok("Your Query submitted Successfully");
return Ok(RedirectToAction("SuccessMessage"));
}

IFormFile in model is always null

I have a file upload form to be submitted.And Below is the ViewModel and it's DataAnnotations. Upon the form submit, the ModelState is getting false. When checked for File property in the ViewModel, it is null. Despite I kept the enctype="multipart/form-data, I'm still getting null.
Could anyone please help me.
public class ExcelUploadViewModel
{
/// <summary>
/// Gets or Sets the FileName
/// </summary>
[Required(ErrorMessage = "FileName is required")]
public string FileName { get; set; }
[Required(ErrorMessage = "File is required")]
[DataType(DataType.Upload)]
public IFormFile File { get; set; }
}
Controller.cs
[HttpPost]
public async Task<IActionResult> UploadExcel(ExcelUploadViewModel excelUploadModel)
{
if (ModelState.IsValid)
{
// HttpResponseMessage response;
TransactionResultBase transactionResultBase = new TransactionResultBase();
IFormFile file = Request.Form.Files[0];
}
}
And FormUpload.cshtml
<div align="left">
<form id="uploadForm" enctype="multipart/form-data" name="uploadForm" asp-action="UploadExcel" method="post" >
<div class="form-group form-group-lg form-group-sm row " >
<div class="col-sm-12 col-md-10 col-lg-10 uploadDiv" style="display: flex !important">
<label asp-for="FileName" class="col-sm-12 col-md-10 col-lg-10" style="font-size: 15px; max-width: fit-content ">File Name :</label>
<input asp-for="FileName" class="form form-control fileName"
type="text"
name="fileName"
placeholder="Enter your file name"
id="fileName" />
<span asp-validation-for="FileName" class="text-danger"></span>
<input asp-for="File" required class="form-control file" type="file" placeholder="File Name" id="file" name="uploadFile" />
</div>
</div>
<small>Please upload .xls or .xlxs or json or xml formatted files only</small>
<div class="form-group form-group-lg form-group-sm row">
<div class="col-sm-12 col-md-10 col-lg-10">
<input type="submit" class="btn btn-primary" name="submit" id="fileUploadButton" value="Upload" />
<input type="reset" class="btn btn-Gray" name="result" id="resetButton" value="Reset" />
</div>
</div>
</form>
</div>
Tag helpers produce id and name attiribute according to the model. So dont use both tag helpers and name attiribute at the same time.
If you want to use tag helper asp-for is enough.If you want to use "name" attiribute then you should use it according to your model and property name. In this situation since you used name attiribute for file input name="uploadFile" your model cannot determine which property is that, so you should correct it name="File"
Be careful it changes if you are using viewmodel in the view.

how to send last id of table and send to blade file in larvel 5.7?

I am fetching last_id from table now i want to send from controller to view. I got the following error
"htmlspecialchars() expects parameter 1 to be string, object given (View: D:\xampp\htdocs\playout\resources\views\category.blade.php)
"
Controller:
public function categoryLastId()
{
$category_type_id = DB::table('table_category_type')->orderBy('category_type_id','DESC')->first();
return view('category',compact('category_type_id'));
}
Blade:
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<label class="col-sm-2 col-form-label">Category id</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Category Id" name="id" readonly value="{{ $category_type_id}}">
</div>
</div>

Meteor Select in form questions?

I have 2 select items in one form Country's and States, depending on the choice made in Countrys the second select as other values (of states) in it !
This works when i do it in a empty form. with code here under :
Template.registerPartnerStep2.events({
'change #countryList': function (event, template) {
event.preventDefault();
var x = myTrim($("#countryList").val());
var y = Countrys.findOne({country: x});
var z = y.nr;
if(template.stateSub != null){
template.stateSub.stop();
}
template.stateSub = Meteor.subscribe('stateList', z);
},
'change #stateList' : function(event, template) {
event.preventDefault();
var x = myTrim($("#stateList").val());
if (template.citySub != null) {
template.citySub.stop();
}
template.citySub = Meteor.subscribe('cityList', x);
},
A part of my template :
{{#with addressFormData}}
<form id="partnerAddressForm" class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"Company"}}</label>
<div class="col-sm-10">
<input type="text" placeholder="{{_"Company name"}}" id="company" class="form-control" value="{{partner_company}}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"VAT nr"}} </label>
<div class="col-sm-10">
<input type="text" placeholder="{{_"VAT nr"}}" id="vatNr" class="form-control" value="{{partner_vat_nr}}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"Phone"}}"</label>
<div class="col-sm-4">
<input type="text" placeholder="{{_"Phone"}}" id="phoneNr" class="form-control" value="{{partner_phone_nr}}">
</div>
<label class="col-sm-2 control-label" for="textinput">{{_"Mobile"}}</label>
<div class="col-sm-4">
<input type="text" placeholder="{{_"Mobile"}}" id="mobileNr" class="form-control" value="{{partner_mobile_nr}}">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"Line 1"}}</label>
<div class="col-sm-10">
<input type="text" placeholder="{{_"Address Line 1"}}" id="addressLine1" class="form-control" value="{{partner_address_line_1}}">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"Line 2"}}</label>
<div class="col-sm-10">
<input type="text" placeholder="{{_"Address Line 2"}}" id="addressLine2" class="form-control" value="{{partner_address_line_2}}">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"Country"}}</label>
<div class="col-sm-10">
<select id = "countryList" placeholder="{{_"Country"}}" class="form-control">
<option disabled selected>{{_"-- select an option --"}} </option>
<option selected="selected">{{partner_country}}</option>
{{#each countrys}}
{{> country}}
{{/each}}
</select>
</div>
</div>
<!-- Text input STATE ZIPCODE-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"State"}}</label>
<div class="col-sm-4">
<select id = "stateList" placeholder="{{_"State"}}" class="form-control" value="{{partner_state}}">
<option disabled selected>{{_"-- select an option --"}}</option>
<option selected="selected">{{partner_state}}</option>
{{#each states}}
{{> state}}
{{/each}}
</select>
</div>
<label class="col-sm-2 control-label" for="textinput">{{_"zipcode"}}</label>
<div class="col-sm-4">
<input type="text" id=zipcode placeholder="{{_"zipcode"}}" class="form-control" value="{{partner_zipcode}}" readonly>
</div>
</div>
<!-- Text input CITY-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">{{_"City"}}</label>
<div class="col-sm-10">
<select id = "cityList" placeholder="City" class="form-control" value="{{partner_city}}">
<option disabled selected>{{_"-- select an option --"}} </option>
<option selected="selected">{{partner_city}}</option>
{{#each citys}}
{{> city}}
{{/each}}
</select>
</div>
</div>
<!-- Button SUBMIT-->
<div class="col-sm-12 controls">
Question ONE is how can i fix it to let this work in EDIT mode when there are already values in the select ????
I fill the selects with :
{{partner_country}}
But this gives already a problem that when i choose in the list the selected value is listed 2 times ?
Second problem : Because the event is Change the statelist shows only one (the selected) state ! When is add a event click #statelist i must always click 2 times on the list before it is filled up with the collection ?
thanks !
I suppose the main point is that you shouldn't be worrying about filling the selects. We don't have to touch the DOM any more, because Meteor reacts by itself if you set it up properly.
You just need to set the selects to be filled from your collections, and then ensure that Meteor reacts when the selects change.
There are many things that are automatically reactive in Meteor - they just work. For example, if your template is showing a list of records, and someone inserts a new record in the database, Meteor will simply show the new record, because Blaze reactively shows newly inserted records.
I try as far as possible to just use the automatically reactive objects that Meteor provides out of the box.
However in our case I have used a Session variable (another reactive source) to ensure that Meteor reacts.
Whenever the countries select changes, we set a 'statenr' session variable. We use the same session variable in our states helper to get the states from the states collection. Since our session variable is reactive, whenever it changes Meteor goes back to the states collection and fetches the states again. Thus our states select object is changed for us by Meteor, we don't have to refill, so we don't have the problem of duplicate states.
I've done a meteorpad example for you so you can see what I mean:
http://meteorpad.com/pad/nccZTcPZx2k8H4XjF/select%20state%20example
To get the chosen country and state into the selects you need this code:
Template.registerHelper('selected', function(key, value){
return key == value ? {selected:'selected'}: '';
});
which I got from this slightly out-of-date page (2nd answer)
Set the selected item in a select list based on template value
and you call the helper (see {{selected partner.statenr nr}}) from your template in each <option> like this:
<select id="partnerStates">
<option disabled selected value="">Choose a state</option>
{{#each states partner.countrynr}}
<option value="{{nr}}" {{selected partner.statenr nr}}>
{{name}}
</option>
{{/each}}
</select>
If you go back to the meteorpad you can see it work in the lower half of the page. On startup I fill a partner record with Germany and Ost-Friesland nrs, then display it in the template in the lower half of the page.

Resources