asp-validation-summary shows custom but not model errors - asp.net-mvc

Asp-validation-summary in view shows errors added via ModelState.AddModelError, but don't show any model validation errors ("The User field is required.").
I'm using Microsoft.AspNetCore.Mvc 1.0.0-rc2-final.
Btw: User field is not displayed via the view but correctly identified by EF as a model level error before add.
//<div asp-validation-summary="ModelOnly" class="text-danger"></div> in view
ModelState.AddModelError(string.Empty, "This error shows up in validation-summary");
ViewBag.HeaderMessage = "Error: " + string.Join(" - ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
Errors show in field filled via ViewBag but not in validation-summary

Change your html:
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
to
<div asp-validation-summary="All" class="text-danger"></div>

Related

How to change " asp-action=" with your selected Viewbag .Net Core 2.0

I am trying to change the "asp-action= ", unfortunately I could not find anything on the internet...
Currently I am working with a ViewBag where I can select a value from that list.
What I want is: I want to put that selected value from the ViewBag in the "asp-action= ( here ) "
Image of my index
Image of my Post method
<form method="post" enctype="multipart/form-data" asp-controller="Parser" asp-action= "PostDrone">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<select asp-items="#(new SelectList(#ViewBag.listofitems ))"></select>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
For example:
I want the "asp-action=" have the string value "PostSchoen" if I selected PostSchoen from the viewbag selectlist
I hope it is understandable what i said
What you wants to do it should doing by client side development with JS
But you have three ways:
1) You can change it by using JS
here an example with Jquery
need add it to onReady function this will change action to option val
<script>
$(function() {
$("select").change(function (){
//set form action to option val or get to whatever you need
$(this).closest("form").attr("action",$(this).val());
});
});
</script>
2) Send data to one contoller method then switch it by your select or other options
change in view
<select name="typeOfUploading" asp-items="#(new
SelectList(#ViewBag.listofitems ))"></select>
change in controller
PostDrone(List<IFromFile> files, string typeOfUploading)
{
//and use typeOfUploading this will be selected value from your select list
}
3) Firstly provide for user this data send choise, that generate him correct view with needed action

asp.net core mvc application form post with query string parameters

I am building a login form in .net core mvc. Below is my login form
<form class="c-form" asp-controller="Account"
asp-action="Login">
<div class="form-group">
#Html.TextBoxFor(m => m.Username, new { #class = "form-control c-input", placeholder = "Username" })
</div>
<div class="form-group">
#Html.PasswordFor(m => m.Password, new { #class = "form-control c-input", placeholder = "Password" })
</div>
<div class="help-text help-text-error">
#Html.ValidationMessage("UserNamePasswordInvalid")
</div>
<div class="">
<button type="submit" class="btn-c btn-teal login-btn width100">Login</button>
</div>
If a form is posted with incorrect credentials user stays on the page with validation failure messages.
Login page also has return url in query string, when the form is posted query string parameters are lost. What is the correct way of doing form post in .net core.
To keep the query string when the form is submitted write a hidden field in the form containing the query string contents:
#Html.Hidden("returnUrl",#Request.QueryString)
Make sure your controller action that handles the post request has a parameter called returnUrl (or the model that is passed as a parameter has that property) and the model binding will take care of passing it through to the controller. Then in the controller action if the login is successful use that data to redirect accordingly.
I know that it's passed a lot of time, but I found a better solution for this problem.
I added a parameter called QueryString in Model as Dictionary string
in view, in tag form, add
So at this time, the post have the parameters in query string<form asp-all-route-data="#Model.QueryString"
Your controller/PageModel method must contain all parameters that you need to persist. Something like this:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
If the controller and action pair for getting and posting the form is the same, than it is simpler to just delete asp-controller and asp-action attributes from the form opening tag, leaving your like this:
<form class="c-form" method="post">

knockoutmvc - unable to parse bindings

I have an ASP.NET MVC site and I am trying to get knockout-mvc working with it.
I have created a View Model in the C# code called Refund that contains among other things a Voucher called Vouchertype and a List<Country> called Countries. Voucher has a variable of type int called VoucherNumber
This View Model is passed into a strongly defined view Refund\Index
I am trying to get knockout-mvc to bind the values in Refund.Voucher.VoucherNumber to a textbox, and the Values in Refund.Countries to a drop-down list. On the controller I have hardcoded the values of Voucher.Vouchernumber and added two countries to the Country list.
Here is my View Code:
#using Resources
#using PerpetuumSoft.Knockout
#model MVC.Models.RefundViewModel
#{
var ko = Html.CreateKnockoutContext();
}
<div id="refundformcontainer">
<div id="headersection">
<div id="pagetitlecontainer">#Language.RefundVouchers</div>
<div id="helpercontainer">
<label id="lblhelper">To begin enter a voucher number or scan a barcode</label>
</div>
</div>
<div id="vouchercontainer">
<div id="voucherdetailscontainer">
<h5>#Language.VoucherDetails</h5>
<div id="vouchernumbercontainer" class="initialvoucherfield">
#Html.LabelFor(x=>x.Voucher.VoucherNumber)
#ko.Html.TextBox(x=>x.Voucher.VoucherNumber)
</div>
<div id="countrycontainer" class="initialvoucherfield">
#Html.LabelFor(x=>x.Voucher.Country)
<select ko.Bind.Options(x=>x.Countries).OptionsText("Name").OptionsValue("CountryId").Value(x=>x.Voucher.CountryId) ></select>
</div>
</div>
</div>
</div>
#ko.Apply(Model);
When the page loads, neither controls are bound to.
When I look at the generated source the following code is generated
<script type="text/javascript">
var viewModelJs = {"Refund":null,"Voucher":{"VoucherId":0,"VoucherNumber":123456789,"Country":null,"CountryId":0,"Retailer":null,"RetailerId":0,"PurchaseDate":"0001-01-01T00:00:00","CustomsStampDate":null,"InvoiceNumber":"","LineItems":[],"TotalPurchasePrice":0.0},"Countries":[{"CountryId":380,"Name":"Italy"},{"CountryId":724,"Name":"Spain"}]};
var viewModel = ko.mapping.fromJS(viewModelJs);
ko.applyBindings(viewModel);
</script>
knockout-2.2.0.js and knockout.mapping-latest.js are both included in the page
The error I am getting is
0x800a139e - JavaScript runtine error: Unable to parse bindings
Message: [Object Error]
Bindings value: Voucher().VoucherNumber
I then changed the Refund View model so it had a property VoucherNumber and had the textbox reference this instead of the Voucher.VoucherNumber property
#ko.Html.TextBox(x=>x.VoucherNumber)
When I ran this I got the same unable to parse bindings error, but this time for the country
Bindings value: options : Countries, optonsText : Name, optionsValue : CountryId
Does anybody have any idea what is causing this?
i think, this should work.
<select #ko.Bind.Options(x=>x.Countries).OptionsText("'Name'").OptionsValue("'CountryId'").Value(x=>x.Voucher.CountryId) ></select>

Disable Required Validation Specific Field in the View ASP.NET MVC 4

if someone could give me some hint I would appreciate.
I'm searching for a while, and I even found a post I thought it would solve my problem, but it didn't.
Disable Required validation attribute under certain circumstances
Basically I have a simple User.cs model where I have username, FirstName, LastName and SignupDate
All have the required annotation and I would like to solve this without erasing the Required tag.
After I generate the view, I erase in the view the html code for the SignupDate:
<div class="editor-label">
#Html.LabelFor(model => model.SignupDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SignupDate)
#Html.ValidationMessageFor(model => model.SignupDate)
</div>
When I click submit it does not work.
Also if I do the suggested in the other post
<div class="editor-label">
#Html.LabelFor(model => model.SignupDate)
</div>
<div class="editor-field">
#Html.TexBoxFor(model => model.SignupDate, new { data_val = false })
</div>
If I leave it as blank also does not work..
Any suggestions? Thanks!!
You can disable client validations on the view and remove the errors on the modelstate for those entities you don't want to validate the value.
In my case I wanted to change a Password only if the user typed one. Using Html.HiddenFor was not a good approach due to sends the password to the client every time, and password shouldn't be sent.
What I did was to disable the client validations on the view
#model MyProject.Models.ExistingModelWithRequiredFields
#{
ViewBag.Title = "Edit";
Html.EnableClientValidation(false);
}
That allows me to submit the form even with empty values. Please note that all client validations are ignored, however server validations still run, so you need to clear those you don't need to be executed. In order to do this, go to the action in the controller and remove the errors for each property you need to
public ActionResult Edit(ExistingModelWithRequiredFields updatedModel)
{
var valueToClean = ModelState["RequiredPropertyName"];
valueToClean.Errors.Clear();
if(ModelState.IsValid)
{
...
//Optionally you could run validations again
if(TryValidateModel(updatedModel)
{
...
}
...
}
...
}
I think this should solve it, assuming model.SignupDate holds a value:
<%: Html.HiddenFor(model => model.SignupDate) %>

MVC3 razor syntax passing a parameter from a link to reset variable inside if statement

Forgive me if this seems like a simple task, I'm fairly new to this...
I'd like to create logic that allows the user to display or not display their email address when editing it from a dialog box. I am placing the link that will allow the user to 'opt out' inside the dialog box - and I'm trying to use the link to reset the variable inside the 'if' statement to 'false' The 'if' statement prevents the email address from being rendered.
Here is my if statement:
<div id="change-email" class="text">
#{
var showEmail = true;
if (showEmail == true)
{
<text><p><span class="label">My email address: </span>#Model.Email</p></text>
}
else (showEmail == false)
{
<text><p>No email displayed</p></text>
}
}
</div><!--#change-email-->
And here is the dialog box code:
<div id="dialog-email" class="modal">
#using (Html.BeginForm("ChangeEmail", "Account", FormMethod.Post))
{
<fieldset>
// form code here
</fieldset>
}
<p>Do not display my email address.</p>
</div>
Any help would be appreciated...
Thanks!
If you do this with jQuery, and you were okay with the email address still being available in the page source, it would look like this:
<div id="change-email" class="text">
<p><span class="label">My email address: </span>#Model.Email</p>
</div>
<div id="dialog-email" class="modal">
#using (Html.BeginForm("ChangeEmail", "Account", FormMethod.Post))
{
<fieldset>
// form code here
</fieldset>
}
<p>Do not display my email address.</p>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('a.no-display').click(function(){
$('#change-email p').text('No email displayed.');
});
});
</script>
It would be a bit more involved if you wanted to persist the preference to not display email. You would probably want to add "Do not display my email address" as a check-box in the ChangeEmail form, adjust the Controller Action to which the form posts to handle the preference, and return it as a variable in the ViewBag of the View that the Action returns.

Resources