Data validation message appears even when textbox has data - c#

So I populated my ABCViewModel with data. Every single field of it had data.
One of its field is called Name. Name is required by using data annotations. [Required]
I passed ABCViewModel to my view, with the name field containing a string.
This view is actually used to edit ABCViewModel contents.
The html page appears, with the nametextbox containing the name. But the data validation message appears below the textbox.
[Name field is required]
When I use my mouse to click on the textbox to grant it focus, the validation message disappears.
Any one had this issue before?
[HttpPost]
public ActionResult Edit(ABCDetailsViewModel abcDetailsViewModel)
{
ABCViewModel abc = new ABCViewModel(abcDetailsViewModel);
return View(abc);
}
#model ABCViewModel
#using(Html.BeginForm("ABCUpdate", "Details", FormMethod.Post, new{name="form", id="form", #class="form-horizontal"}))
{
#Html.AntiForgeryToken()
#Html.LabelFor(model=>model=>Name, new{#class="control-label col-sm-2"})
#Html.TextBoxFor(model => model.Name, "", new{#style="width:100%;"})
#Html.ValidationMessageFor(model => Model.Name, "", new{#class = "alert-danger"})
.
.
.
}

Check whether you pass an object empty object with null values in your return View() method - recheck that you didn't set any default value for Name prop
If nothing works please post your cshtml and the controller code
In your Html.EditFor() method check that you are not binding any values - Thanks

Related

Sending the key pressed to the server

I have the following code:
#Html.EditorFor(model => model.AssociatedCard, new { htmlAttributes = new { #class = "form-control", #id="addCardBox", #onkeydown="test()"} })
Notice the #onkeydown="test()" attribute. This works fine, on keydown, a JS function is called.
But I want to send the key that was pressed, to the server, and save it to the database.
How can I send this key to the server, so that I can handle it in the C# code?
In asp.net, we can do something like this (which will allow me to bind to the TextBox):
<asp:TextBox id="txt" Runat="Server"></asp:TextBox>
At server side, I can then reach my textbox with the id=txt. Can I do something similar, without having to use ajax/JQuery?
Provided EditorFor is producing a textbox you can do the following as it will capture the input.
You appear to be on the right track given that you've created a strongly typed view, you just need to wrap your inputs in a form to post them to the server.
#using (Html.BeginForm("PostAction", "Home"))
{
//Put your foreach loop in here
}
Then in your controller
public class HomeController : Controller
{
[HttpPost]
public ActionResult PostAction(ViewModelType model)
{
//model.AssociatedCard should contain your value
}
}

Lost remaining record after validation error comes in MVC

I have one MVC project,containing user registration form which have 25-30 fields to fill. After filling form if user forgot to fill mandatory field then it will shows validation error. But remaining all fields loss their data.
I mentioned in controller like
if (!ModelState.IsValid)
{
ModelToDBclass obj = new ModelToDBclass();
objModel.Id = Convert.ToInt32(obj.GetMaxPaperId());
objModel.countryNameDB = obj.GetcountryName();
return View(objModel);
}
and finally it returns the blank view. but at runtime when it comes to
return View(objModel); , the model shows the data with every field, but when it comes to view it unable to show record in text boxes and dropdown. I used textbox like,
<div class="col-sm-2"><input type="text" class="form-control" name="ConsumerFName" id="txtConsumerFirstName" placeholder="First Name" />
#Html.ValidationMessageFor(m => m.ConsumerFName)</div>
so, please help me how can i display filled record after validation error
You should always use Html Helper
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" }, placeholder = "First Name", autofocus = "autofocus" })
Then only when the Model state is not valid, it will show the returned object values at the respective fields. Don't normal html tags.
Hope this helps

MVC Validation - Server side validation won't allow resubmit using Kendo

Our application (MVC5) has some very complex validation that needs to be done server side (compound capacity checks, workflow validation, and more). The problem we are running into is that once server side validation fails and returns to the same view, the client side never submits values for any fields again (0 for int, empty strings, etc.)
Our general pattern is as follows:
public ActionResult PerformSomeAction()
{
var model = GetActionTemplate();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PerformSomeAction([Bind(Include = ActionTemplate.FIELDS)] ItemTemplate template)
{
string errorMessage;
if (ModelState.IsValid)
{
bool isValid = ValidateAndPerformAction(template, out errorMessage)
if(isValid)
return RedirectToAction("Action", "Controller");
}
// Reset non-bound fields from new template
var model = GetActionTemplate();
template.FieldValue = model.FieldValue
return View(template);
}
Our views don't have anything special in them, other than the fact that some of our editors are built with the Telerik Kendo library. However, the symptoms are seen for all controls, not just Kendo based ones.
A basic View layout for editing a field is as follows:
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.Kendo().TextBoxFor(model => model.Name).HtmlAttributes(new
{
title = ModelMetadata.FromLambdaExpression(model => model.Name, ViewData).Description
})
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
Does anyone have any suggestions on what we are doing wrong?
Note: While it could be argued that this validation could be triggered through AJAX or other service calls, we would prefer to do it with the post implementation that we are using.
Update:
After further research, it appears this has to do with Kendo and not MVC. If I switch my View to be the following:
#Html.EditorFor(model => model.Volume)
Instead of:
#Html.Kendo().NumericTextBoxFor(model => model.Volume).HtmlAttributes(new
{
#class = "",
title = ModelMetadata.FromLambdaExpression(model => model.PreBoilVolume, ViewData).Description
}).Value(Model.Volume)
Everything appears to work fine. So somewhere in that Kendo statement it fails to rebind when returning from the post. It doesn't matter if I set the value again manually, it will never send it back in.
I guess it is time to get rid of some Kendo statements and go back to a more basic UI.
What you "want" to do is a very basic scenario for MVC with failed validation.
The first one that always catches people is with drop down lists. The posted model, does not contain the list of items, so has to be re-populated after failed validation, and then passed back into the view on return.
When I can't solve things like this I start commenting stuff out and work forwards. So in this case strip your model back to one non-ID property and see if it will work. Then you can try and track down the culprit.
It looks like the selectedvalues are not set on the model. Try change these lines of code:
var model = GetActionTemplate();
template.FieldValue = model.FieldValue
return View(template);
to something like this:
var model = GetActionTemplate();
model.Selectedvalues = template.FieldValue ?
return View(model);

View is sending null value to the controller

I have a view file from where I am trying to send the url to the controller file
My view file looks like:
#model WebRole1.Models.CodeSnippet
#{
ViewBag.Title = "Details";
}
<p>
#Html.ActionLink("Preview", "Preview", new { Model.URL }) |
</p>
In the above code I am trying to send the url value to the controller file. Function in the controller file looks like
public ActionResult Preview(object zipPath)
{
// some operation...
}
However for some reason view is sending null value to the controller. i.e. when Preview method of controller gets called zipPath value remains null. What can be the issue?
Your action method is waiting for property with the name zipPath. But, since you don't provide a name for a property in your anonymous object, it will be URL by default.
So, change your code to:
#Html.ActionLink("Preview", "Preview", new { zipPath = Model.URL })
Additional information:
If you have included zipPath as a URL segment in your route, then the value will assigned to this segment by the routing segment. Otherwise, the value we supplied will be added as part of the query string.

Transfer Model Data in View to the Controller

I have a model that I am using in my view that is full of data. This data is then edited in the view. I need to figure out a way to resubmit this data back over to the controller.
Here is what I have so far.
VIEW:
#using (Html.BeginForm("DownloadCSV", "Respondents", FormMethod.Post))
{
#Html.HiddenFor(m => m.FilterSet)
<div class="btn btn-default pull-right" id="dispoCSV" onclick="$('#csvFormSubmit').click()">
<i class="icon-file-alt"></i> Disposition Report
</div>
<input id="csvFormSubmit" type="submit" style="display:none;" />
}
CONTROLLER:
[HttpPost]
public ActionResult DownloadCSV(RespondentsFilterSet model)
{
string csv = "Charlie, Test";
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "DispositionReport.csv");
}
MODEL:
public class RespondentsFilterSet : ColdListFilterSet
{
public List<int> OwningRecruiters { get; set; }
public List<int> RecruitingGroups { get; set; }
public override bool HasAtLeastOneFilter()
{
return base.HasAtLeastOneFilter() || OwningRecruiters.IsNotNullOrEmpty() || RecruitingGroups.IsNotNullOrEmpty();
}
public override ExpressionBase ToExpression()
{
var expr = base.ToExpression();
var expressions = expr == null ? new List<ExpressionBase>() : new List<ExpressionBase> { expr };
if (OwningRecruiters.IsNotNullOrEmpty())
{
expressions.Add(new InExpression<int> { Field = Create.Name<Respondent>(r => r.RecruitedBy), Values = OwningRecruiters });
}
if (RecruitingGroups.IsNotNullOrEmpty())
{
expressions.Add(new InExpression<int> { Field = Create.Name<Respondent>(r => r.RecruitingGroupId), Values = RecruitingGroups });
}
return expressions.Count == 0 ? null : BuildAndExpressionFromList(expressions);
}
}
I realize that my controller is not not finalized. I just have displaying some static csv. But I can't figure out why my model from my view is always null when returned to the controller.
Just look at your form. There's not a single input element (except the submit button). You cannot expect to get anything back on the server in this case.
Please read about HTML and how forms work in HTML. In HTML forms you have input fields. Things like text fields, hidden fields, checkboxes, radio buttons, ... - fields that the user interacts with get submitted to the server.
The fact that you have made your HttpPost controller action take some model as parameter doesn't mean at all that this parameter will be initialized. In ASP.NET MVC you have a default model binder. This model binder looks at what gets sent to the server as values when the form is submitted and uses the names of the fields to bind to the corresponding properties. Without input fields in the form, nothing gets sent to the server. Just use the debugging tools built into your web browser to inspect what exactly gets sent to the server.
Contrary to classic ASP.NET WebForms, ASP.NET MVC is stateless. There's no ViewState to remember your model.
So all this rambling is to say that you should read more about HTML forms first and understand the stateless nature of the web before getting into ASP.NET MVC. As far as your particular problem is concerned, well, assuming the user is not supposed to modify any values of the view model in your view throughout some input fields, you could simply include a hidden field containing the id of your model in the form. This id will then be sent to your POST controller action as parameter and you could use it to retrieve your original model from wherever it is stored (I guess a database or something).

Categories