How to bind list values(array) in Viewbag - c#

Here i am getting values in viewbag but i am unable to bind the values to fields.And this is my code
#foreach (RankedServices.Business.UIModels.Services cc in ViewBag.selectedCommonCriteria)
{
<div class="row" style="margin-top:10px;">
<div class="col-lg-5">
<div class="form-group">
<label class="control-label col-sm-12">Awards:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="Awards" id="Awards" placeholder="Enter Awards" value="#cc.SelectedCC[0].Awards"/>
</div>
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label class="control-label col-sm-12">Certifications:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="Certifications" id="Certifications" placeholder="Enter Certifications" value="#cc.SelectedCC[0].Certifications" />
</div>
</div>
</div>
</div>
<div class="row" style="margin-top:10px;">
<div class="col-lg-5">
<div class="form-group">
<label class="control-label col-sm-12">Associations:</label>
<div class="col-sm-12">
<input type="text" class="form-control" name="Associations" id="Associations" placeholder="Associations" value="#cc.SelectedCC[0].Associations"/>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label col-sm-12">Share your areas of expertise and how you can best help customers:</label>
<div class="col-sm-12">
<textarea class="form-control" name="AdditionalInfo" id="AdditionalInfo" placeholder="Please tell your customers about your interests, specialities and expertise" rows="2" value="#cc.SelectedCC[0].AdditionalInfo"></textarea>
</div>
</div>
</div>
</div>
}
And i am getting error : "Cannot implicitly convert type 'RankedServices.Business.UIModels.Services' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)"
How should i bind the vlaues.

Assuming your ViewBag.selectedCommonCriteria is an IEnumerable of type Services then you can do this:
#foreach (RankedServices.Business.UIModels.Services cc in (IEnumerable<RankedServices.Business.UIModels.Services>)ViewBag.selectedCommonCriteria)
You're using a ViewBag which is a dynamic object so in order to use it for anything other than what every object can do (for example ToString()) you must cast it to it's appropriate type.

Related

asp-for value (model property) in cshtml file breaks automatically into two parts

asp-for value (model property) in cshtml file breaks automatically into two parts. Help me plz...... example asp-for="SpouseNa tionality" as given in code below....
enter code here
<div class="col-md-6">
<div class="form-group">
<label asp-for="**SpouseNa tionality**" class="control-label"></label>
<input asp-for="**SpouseNa tionality**" class="form-control" />
<span asp-validation-for="SpouseNationality" class="text-danger"></span>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label asp-for="**Residenti alAddress**" class="control-label"></label>
<input asp-for="**Residenti alAddress**" class="form-control" />
<span asp-validation-for="ResidentialAddress" class="text-danger"></span>
</div>
</div>

Validation not working on cloned elements

If I create multiple elements like this...
#for (int i = 0; i < 10; i++)
{
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Railcars[i].RailcarNumber" class="control-label"></label>
<input asp-for="Railcars[i].RailcarNumber" class="form-control" />
<span asp-validation-for="Railcars[i].RailcarNumber" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="Railcars[i].Weight" class="control-label"></label>
<input asp-for="Railcars[i].Weight" class="form-control" />
<span asp-validation-for="Railcars[i].Weight" class="text-danger"></span>
</div>
</div>
</div>
}
Validation appears to work correctly for all rows.
However, if I create a single row like this...
<div class="railcars">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Railcars[0].RailcarNumber" class="control-label"></label>
<input asp-for="Railcars[0].RailcarNumber" class="form-control" />
<span asp-validation-for="Railcars[0].RailcarNumber" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="Railcars[0].Weight" class="control-label"></label>
<input asp-for="Railcars[0].Weight" class="form-control" />
<span asp-validation-for="Railcars[0].Weight" class="text-danger"></span>
</div>
</div>
</div>
</div>
And then clone rows using jQuery's clone(), validation only appears to work for the first (non-cloned) row.
Note: I am taking care to update all the ID, name, and for attributes of the cloned elements, and updating the subscript number. I checked that it's correct and posts the correct information to the server. ModelState even correctly detects validation problems with the cloned elements. It's just that client-side validation doesn't work on them.
Here is the HTML produced:
Uncloned Row (validation works):
<div class="row first-railcar">
<div class="col-md-4">
<div class="form-group railcar-number">
<label class="control-label" for="Railcars_0__Railcar">Railcar Number</label>
<input class="form-control" type="text" data-val="true" data-val-length="The field Railcar Number must be a string with a maximum length of 18." data-val-length-max="18" data-val-required="The Railcar Number field is required." id="Railcars_0__Railcar" maxlength="18" name="Railcars[0].Railcar" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="Railcars[0].Railcar" data-valmsg-replace="true"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group railcar-volume">
<label class="control-label" for="Railcars_0__Volume">Volume (pounds)</label>
<input class="form-control" type="text" data-val="true" data-val-number="The field Volume (pounds) must be a number." data-val-required="The Volume (pounds) field is required." id="Railcars_0__Volume" name="Railcars[0].Volume" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="Railcars[0].Volume" data-valmsg-replace="true"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"> </label><br>
<img class="add-railcar" src="/images/add.png" title="Add Additional Railcar" style="display: none;">
<img class="remove-railcar" src="/images/delete_2.png" title="Remove Railcar" style="display: none">
</div>
</div>
</div>
Cloned Row (validation doesn't work):
<div class="row">
<div class="col-md-4">
<div class="form-group railcar-number">
<label class="control-label" for="Railcars_1__Railcar">Railcar Number</label>
<input class="form-control" type="text" data-val="true" data-val-length="The field Railcar Number must be a string with a maximum length of 18." data-val-length-max="18" data-val-required="The Railcar Number field is required." id="Railcars_1__Railcar" maxlength="18" name="Railcars[1].Railcar" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="Railcars[1].Railcar" data-valmsg-replace="true"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group railcar-volume">
<label class="control-label" for="Railcars_1__Volume">Volume (pounds)</label>
<input class="form-control" type="text" data-val="true" data-val-number="The field Volume (pounds) must be a number." data-val-required="The Volume (pounds) field is required." id="Railcars_1__Volume" name="Railcars[1].Volume" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="Railcars[1].Volume" data-valmsg-replace="true"></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"> </label><br>
<img class="add-railcar" src="/images/add.png" title="Add Additional Railcar">
<img class="remove-railcar" src="/images/delete_2.png" title="Remove Railcar" style="">
</div>
</div>
</div>
I also carefully compared the cloned HTML above to the HTML created by my first example (with the for loop), and they are identical. Apparently, there is something different about it being added after the page has loaded.
Does anyone know how to clone elements this way and have validation work on all the cloned elements?
Update:
My use of jQuery's clone() includes two true values ($row.clone(true, true)). If I don't do this, the click handlers for my images don't work.
As recommended, I tried several variations of the following code after cloning the elements. But I couldn't get it to make any difference.
var form = document.getElementById('input-form');
$.validator.unobtrusive.parse(form);
You are on the right track with $.validator.unobtrusive.parse(form);. However for jQuery Validation to work on copied/appended with ajax/cloned elements you need three things.
Make sure every input element has a unique name.
Remove any previous validation bindings in the form of existing elements.
Re-create the validation bindings.
So here is a working example below.
<form>
<div class="container" id="ElementContainer">
<div id="ElementToClone">
<div class="row">
<div class="col col-md-4">
<div class="form-group">
<input class="form-control" type="text" name="elem[0]" id="elem_0" data-val="true" data-val-required="Required.">
</div>
</div>
</div>
</div>
</div>
<div class="pt-3">
<button type="button" class="btn btn-primary" onclick="Clone()">Clone</button>
<button type="submit" class="btn btn-primary ml-3">Submit</button>
</div>
</form>
<script>
function Clone() {
var $container = $('#ElementContainer');
var $elem = $('#ElementToClone');
var $form = $container.closest('form');
//duplicate x times
for (var i = 1; i <= 5; i++) {
var clonedHtml = $elem.html();
//create a unique name
clonedHtml = clonedHtml.replace('elem[0]', 'elem[' + i + ']');
//create an unique id (not required for validate to function)
clonedHtml = clonedHtml.replace('elem_0', 'elem_' + i);
//append the cloned element
$container.append(clonedHtml);
}
//remove validation from the inital input elements or it won't work
$form.removeData('validator').removeData('unobtrusiveValidation');
//bind the validation again
$.validator.unobtrusive.parse($form);
}
</script>
P.S. tested on MVC, not Core. But it should work the same since it is front-end anyways.

Foreign Key asp.net core with postgress

I have this file upload form
#model FileUploadViewModel
#{
ViewData["Title"] = "Index";
}
<h4>Start Uploading Files Here</h4>
<hr />
#if (ViewBag.Message != null)
{
<div class="alert alert-success alert-dismissible" style="margin-top:20px">
#ViewBag.Message
</div>
}
<form enctype="multipart/form-data" asp-controller="files" asp-action="UploadToFileSystem" method="post">
<div class="form-group row">
<label asp-for="Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Name" class="form-control" placeholder="name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Author" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Author" class="form-control" placeholder="Author" />
<span asp-validation-for="Author" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Genre" class="col-sm-2 col-form-label"> </label>
<div class="col-sm-10">
<select asp-for="Genre" class="custom-select mr-sm-2" asp-items="Html.GetEnumSelectList<Genres>()" ></select>
</div>
</div>
<div class="form-group row">
<label asp-for="Description" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Description" class="form-control" placeholder="Description" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="form-group row " >
<label asp-for="PublishedOn" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input type="date" asp-for="PublishedOn" class="form-control" placeholder="Publishing Date" />
<span asp-validation-for="PublishedOn" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Files" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<div class="custom-file">
<input asp-for="Files" multiple type="file" class="form-control custom-file-input" placeholder="file" />
<label class="custom-file-label">Chose File...</label>
<span asp-validation-for="Files" class="text-danger"></span>
</div>
</div>
</div>
<button class="btn btn-success" type="submit" asp-action="UploadToFileSystem" asp-controller="Files">Upload</button>
</form>
#section Scripts{
<script>
$(document).ready(function () {
$('.custom-file-input').on("change", function () {
var fileLabel = $(this).next('.custom-file-label');
var files = $(this)[0].files;
if (files.length > 1) {
fileLabel.html(files.length + 'files selected');
}
else if (files.length == 1) {
fileLabel.html(files[0].name);
}
});
});
</script>
}
I want to make dropdown list with this table from postgresql database
FileTypes table in pgadmin
And i have this table for genres in database
Genres table in pgadmin
So if i pick FileType with ID=1 in first dropdown,in the second dropdown i want to show only genres with with FileTypeID=1,I try to fill the genres table manualy but i have error(will be posted below).Any help for this way,or other way to filter genres dropdown depends on file type selected in first dropdown.Error trying to fill rows in Genre table
Based on that error, you didn't create a foreign key but a unique index on that column in the Genre table. They prefix IX for index and FK for foreign keys by default I believe. Check your table relationships and check IX_genres_FileTypesID and I am pretty sure you will see the relationship isn't there.

Error in form POST: Model bound complex types must not be abstract or value types and must have a parameterless constructor

I'm getting an error while running my project and sending a POST through my Register.cshtml View. See the error below:
InvalidOperationException: Could not create an instance of type 'AdoteRJ.Models.Adotante'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'model' parameter a non-null default value.
Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
This error started happenning after I refactored MyEntity class (Adotante), adding some complex types, in order to make it a rich domain. For some reason I have not discovered yet, this error started and the POST gets an error 500, although the Form Data is successfully filled (I checked it on dev tools' headers)
I'm using .NET Core 2.1
Also, I found this question below, with the same problem, but it's answer does not resolve it - if you add an empty constructor, the error disappears, but the form is sent empty...
Model bound complex types must not be abstract or value types and must have a parameterless constructor
My code:
public class Adotante : Entity
{
public Adotante(
Email email,
string senha,
NomeCompleto nomeCompleto,
string foto,
Lar lar
)
{
Email = email;
Senha = senha;
NomeCompleto = nomeCompleto;
Foto = foto;
Lar = lar;
}
public Email Email { get; private set; }
[DataType(DataType.Password)]
[StringLength(100, MinimumLength = 6)]
public string Senha { get; private set; }
public NomeCompleto NomeCompleto { get; private set; }
public string Foto { get; private set; }
public Lar Lar { get; private set; }
#region Adotante Métodos
public void SetEmail(Email email)
{
email = this.Email;
}
#endregion
}
An example of one of my ValueObject classes:
public class Email : ValueObject
{
public Email() { }
public Email(string enderecoEmail)
{
EnderecoEmail = enderecoEmail;
}
[Display(Name = "E-Mail")]
[Required(ErrorMessage = "Por favor, insira o e-mail do usuário/adotante")]
[EmailAddress]
public string EnderecoEmail { get; private set; }
}
}
The form on my Register.cshtml class:
<div class="row">
<form asp-controller="Account" asp-action="Register" asp-route-returnurl="#ViewData["ReturnUrl"]" method="post" class="form-horizontal">
<div class="col-md-1">
<!-- Gap between columns -->
</div>
<div class="col-md-4">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">email</i></span>
<div class="form-line">
<input asp-for="Email.EnderecoEmail" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Senha" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">lock</i></span>
<div class="form-line">
<input asp-for="Senha" class="form-control" />
<span asp-validation-for="Senha" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="NomeCompleto" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">person</i></span>
<div class="form-line">
<input asp-for="NomeCompleto.Nome" class="form-control" />
<span asp-validation-for="NomeCompleto" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Foto" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">insert_photo</i></span>
<div class="form-line">
<input asp-for="Foto" class="form-control" />
<span asp-validation-for="Foto" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Lar.RendaMensal" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">attach_money</i></span>
<div class="form-line">
<input asp-for="Lar.RendaMensal" class="form-control date" />
<span asp-validation-for="Lar.RendaMensal" class="text-danger"></span>
</div>
<span class="input-group-addon">,00</span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Finalizar Cadastro" class="btn btn-primary btn-lg" />
</div>
</div>
<div class="col-md-1">
<!-- Gap between columns -->
</div>
<div class="col-md-4">
<div class="form-group">
<label asp-for="Lar.PessoasNaCasa" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">home</i></span>
<div class="form-line">
<input asp-for="Lar.PessoasNaCasa" class="form-control" />
<span asp-validation-for="Lar.PessoasNaCasa" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Lar.MetragemCasa" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">home</i></span>
<div class="form-line">
<input asp-for="Lar.MetragemCasa" class="form-control" />
<span asp-validation-for="Lar.MetragemCasa" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Lar.TipoLar" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">home</i></span>
<div class="form-line">
<select asp-for="Lar.TipoLar" asp-items="Html.GetEnumSelectList<TipoLar>()">
<option value="" selected disabled hidden>Selecione</option>
</select>
<span asp-validation-for="Lar.TipoLar" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Lar.CasaComTela" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">home</i></span>
<div class="form-line">
<select asp-for="Lar.CasaComTela" asp-items="Html.GetEnumSelectList<CasaComTela>()">
<option value="" selected disabled hidden>Selecione</option>
</select>
<span asp-validation-for="Lar.CasaComTela" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Lar.TemCriancas" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">home</i></span>
<div class="form-line">
<select asp-for="Lar.TemCriancas" asp-items="Html.GetEnumSelectList<TemCriancas>()">
<option value="" selected disabled hidden>Selecione</option>
</select>
<span asp-validation-for="Lar.TemCriancas" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="Lar.TemAnimais" class="control-label"></label>
<div class="input-group">
<span class="input-group-addon"><i class="material-icons">home</i></span>
<div class="form-line">
<select asp-for="Lar.TemAnimais" asp-items="Html.GetEnumSelectList<TemAnimais>()">
<option value="" selected disabled hidden>Selecione</option>
</select>
<span asp-validation-for="Lar.TemAnimais" class="text-danger"></span>
</div>
</div>
</div>
</div>
</form>
</div>
Using [FromBody] attribute for the incoming request model parameter in the action method might help. Something like this:
[HttpPost]
public void Post([FromBody] Adotante incomingRequest)
{
\\posting logic here
}

How to store multiple textbox values into one application variable in c#

[code page="c#"]
Hdnano.Value = Application["AccountNum"].ToString();
$(document).ready(function() {
$("#ano").on("blur", function() {
var accountNum = $('textarea#ano').val();
$("#Hdnano").val(folioNum);
});
<html>
<body>
<form>
<div class="container">
<div class="row">
<div class="col-xs-3 col-lg-2">
SELECT bank name
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-xs-3 col-lg-2">
father name
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
<div class="col-xs-3 col-lg-2">
father mobile no
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-xs-3 col-lg-2">
mother name
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
<div class="col-xs-3 col-lg-2">
mother mobile no
</div>
<div class="col-xs-3 col-lg-3">
<input id="Text1" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-xs-3 col-lg-2">
Account numbers
</div>
<div class="col-xs-3 col-md-6 col-lg-6">
<textarea class="form-control" rows="5" id="fno"></textarea>
</div>
</div>
</div>
</form>
</body>
</html>
How to store multiple textbox values into one application variable ?
here Customer details which are select bank name ,father/mother name and mobile number into one application variable ,and the multiple account numbers which is in text area into second application variable ?I want to store values of customer into application variable and than want to pass this values onto other page which is also similar kind of this html page.How can I use here json string
You can name variables like array elements. Look at this:
<form action="" method="POST">
<input type="text" name="name1[first]">
<input type="text" name="name1[second]">
<input type="text" name="name1[third]">
<input type="text" name="name2[0]">
<input type="text" name="name2[1]">
<input type="submit">
</form>

Categories