I have to set a price either a double or decimal.
I get this error and I have tried all I know.
Model:
public double price { get; set; }
Controller create:
public ActionResult Create([Bind(Include = "ID,farmID,productID,price, URL")] ProductFarm productFarm) {
if (ModelState.IsValid) {
db.farmProducts.Add(productFarm);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.farmID = new SelectList(db.farms.OrderBy(x => x.farmName), "farmID", "farmName", productFarm.farmID);
ViewBag.productID = new SelectList(db.products.OrderBy(x => x.productName), "productID", "productName", productFarm.productID);
return View(productFarm);
}
Edit - added view code:
<div class="form-group">
#Html.LabelFor(model => model.price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.price, "", new { #class = "text-danger" })
</div>
</div>
This error is basically a locale issue. You have to set which locale you want to target to. By default the MVC scaffolding will default to your PC's culture.
You can set culture in your web.config
<system.web>
<globalization culture ="en-US" />
</system.web>
Since the issue is from the jquery validate plugin you can install jquery.validate.globalize
Install-Package jQuery.Validation.Globalize
Show's you how to use it https://johnnyreilly.github.io/jQuery.Validation.Unobtrusive.Native/AdvancedDemo/Globalize.html
Or,
You can extend your jquery.validate plugin yourself http://www.cedricascoop.be/blog/2011/10/22/mvc-3-problems-validating-a-decimal/
number: function (value, element) {
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value); //dot separated
return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value); //comma separated
}
above code is from jquery.validate.js around line 1050 you can see the validation.Don't be confused I added the second return. I switched the return statement around. One return validates for dot another for comma.
Related
I'm currently writing an ASP.Net MVC application
I've successfully made an input box in CSHTML.
#Html.EditorFor(model => model.Test, new { htmlAttributes = new { #class = "form-control"} })
I now want to take the content of a string from the controller and add is as placeholder text. I've tried the following
#Html.EditorFor(model => model.Test, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayFor(model => model.Test) } })
But that set the placeholder like so: placeholder=""
If I instead use #Html.DisplayNameFor it sets the placeholder to the variable's name Test, but I want the actual string content. I'm aware that one can use the Viewbag to pass text to the view, but there must be a way of doing it this way.
Any help is greatly appreciated.
You can't use #Html.DisplayFor() as a placeholder but you can use Html.DisplayNameFor().
Example:
#Html.EditorFor(model => model.Test, new { htmlAttributes = new { #class = "form-control", #placeholder = "Your Place Holder" } })
OR
#Html.EditorFor(model => model.Test, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayNameFor(model => model.Test) } })
I think you need to add the [Display (name="Your Text")] attribute in the propriety of the model like this:
[Display (Name="Name Of Client:")]
Public string Name {get; set;}
Make a Property in your Model which you are passing to view.
Assign the string into that property.
Model.SomeName= YourVariableName;
Then Try Like This :-
#Html.EditorFor(model => model.Test, new { htmlAttributes = new { #class = "form-control", placeholder = #Model.SomeName }
I inherited an MVC site and was asked to combine two pages into one. Since both Views have their own View Model, I thought instead of pushing the two VMs together that I could use a Partial View to display, in this case, the Clock Group in a View called Clock_Detail. However, I need to get the GroupId to populate the data for the Clock Group.
So, having rarely used Partial Views I’m confused on how to get this to work.
I created a new View called _ClockGroup.cshtml and just copied and pasted some basic code from the other page just to see if I could get anything to display.
In my ClockDetail controller I added the following.
public PartialViewResult ClockGroup(int groupId)
{
ClockGroupViewModel vm = DAL.GetClockGroupDetail(groupId);
return PartialView(vm);
}
Here is _ClockGroup.cshtml
#model site.Models.ViewModels.ClockGroupViewModel
<div class="form-group">
#Html.LabelFor(m => m.GroupId, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(m => m.GroupId, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
</div>
<div class="form-group">
#Html.LabelFor(m => m.GroupName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(m => m.GroupName, new { htmlAttributes = new { #class = "form-control", autofocus = "autofocus" } })
#Html.ValidationMessageFor(m => m.GroupName, "", new { #class = "text-danger" })
</div>
This is from the clock_detail.cshtml view. It uses the following Model and then I added the Partial to this view.
#model site.Models.ViewModels.ClockDetailViewModel
#Html.Partial("_ClockGroup")
Of course I get an error that the model passed a dictionary type “site.Models.ViewModels.ClockDetailViewModel” but the dictionary requires a model item of time “site.Models.ViewModels.ClockGroupViewModel".
Will I need to go ahead and combine the two ViewModels together and just use the single ViewModel?
When you do not specify an object as the second parameter:
#Html.Partial("_ClockGroup")
It automatically passes the current model which is of type ClockDetailViewModel
Your partial requires type ClockGroupViewModel
The fix would be when you call the partial to pass in the ClockGroupViewModel property of your ClockDetailViewModel object:
#Html.Partial("_ClockGroup", Model.ClockGroupViewModelProperty)
If your ClockDetailViewModel class does not have a ClockGroupViewModel property, you will need to add that to your ViewModel and populate the data.
I created this simple ASP.NET project. (Default template using MVC)
In there I generated models from my database using ADO.net
I also generated controller for my model. (The model generated functions for create, edit, delete...) I also got view for every function in the controller.
So what I am trying to do now is:
-I am in my create view. (that means I see my form for creating objects)
-I need to enter data for [title, content] but to post in database I also need an id (this id is a foreign key, not the id of the object i am creating)
I already have this id saved in my session. I can access the session data by doing:
var user = Session["user"] as Uporabniki; //returns session data
user.id //selects id from session
Now what I want is to use this id in the create form textbox.
As of now the rows for id in my view look like this (I have no idea why it's a dropdown list. When I open the site I see names of all users in database and I can select one. But this is not what I want. I want to see only one):
<div class="form-group">
#Html.LabelFor(model => model.id_avtorja, "id_avtorja", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("id_avtorja", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.id_avtorja, "", new { #class = "text-danger" })
</div>
</div>
The create methods in controller look like this
// GET: Vprasanjas/Create
public ActionResult Create()
{
ViewBag.id_avtorja = new SelectList(db.Uporabniki, "id", "uporabniskoIme");
return View();
}
// POST: Vprasanjas/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,naslov,vsebina,datum,id_avtorja")] Vprasanja vprasanja)
{
if (ModelState.IsValid)
{
db.Vprasanja.Add(vprasanja);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.id_avtorja = new SelectList(db.Uporabniki, "id", "uporabniskoIme", vprasanja.id_avtorja);
return View(vprasanja);
}
Why is it not working if I change the view to something like this:
<div class="form-group">
#Html.LabelFor(model => model.id_avtorja, "id_avtorja", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#var user = Session["user"] as Uporabniki;
#Html.Raw(user.id)
#Html.ValidationMessageFor(model => model.id_avtorja, "", new { #class = "text-danger" })
</div>
</div>
And how can I fix this?
Try rewrite to
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,naslov,vsebina,datum,id_avtorja")] Vprasanja vprasanja)
{
if (ModelState.IsValid)
{
vprasanja.id = (Session["user"] as Uporabniki).id;
db.Vprasanja.Add(vprasanja);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.id_avtorja = new SelectList(db.Uporabniki, "id", "uporabniskoIme", vprasanja.id_avtorja);
return View(vprasanja);
}
Main idea - assign your id on post.
Please post some info on the error. But my guess is you aren't creating any input HTML element so there's nothing posting. You need something like <input type="hidden" id="id_avtorja" value="#user.id"> in the form.
Also, I'd advise against using data out of a session variable. That's older technology and very un-MVC in philosophy.
I have following GET method , that's a code to a create form
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct();
return View(sample);
}
this is the model class for that
public class AddNewProduct
{
public string Product_ID { get; set; }
...
}
this is that create form
#model project_name.Models.AddNewProduct
<h4>Add New Product</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" }) <div class="form-group">
#Html.LabelFor(model => model.Product_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Product_ID, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Product_ID, "", new { #class = "text-danger" })
</div>
</div>
.....
<div>
#Html.ActionLink("Back to AddNewProduct", "AddNewProduct","Home" , new {Product_ID = Model.Product_ID})
</div>
}
I can Insert a Product_ID using this view page .But Once I click this Back to AddNewProduct link and debug AddNewProduct I cannot see any value for string Product_ID
Why this model properties not bind well
You need to assign value. Assign value of Product_ID which you are sending from get method to Product_ID property of class
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct();
sample.Product_ID = Product_ID;
return View(sample);
}
To pass the value of the textbox to the Add_Product() GET method, you need to use javascript/jquery. Replace you #Html.ActionLink(..) with
Back to AddNewProduct
and add the following script
var baseUrl = '#Url.Action("Add_Product", "Home")';
$('#back').click(function() {
var id = $('#Product_ID').val();
location.href = baseUrl + '/' + id;
}}
Note: location.href = baseUrl + '/' + id; assumes your have defined a specific route with {controller}/{action}/{Product_ID}, otherwise it needs to be
location.href = baseUrl + '?Product_ID=' + id;
Alternatively, change the method parameter to string id so it uses the default route
Note also that you will probably want to change the method to
public ActionResult Add_Product(string Product_ID)
{
AddNewProduct sample = new AddNewProduct
{
Product_ID = Product_ID
};
return View(sample);
}
so that if you click the Back to AddNewProduct link, the view will display the previous value you entered.
The second parameter of the #Html.ActionLink is the actionName but you sent the model name (AddNewProduct). Change it to this:
#Html.ActionLink("Back to AddNewProduct", "Add_Product","Home" , new {Product_ID = Model.Product_ID})
Or use this overload (You need to send null also when using this ActionLink overload):
#Html.ActionLink("Back to AddNewProduct", "Add_Product","Home" , new {Product_ID = Model.Product_ID}, null)
I am filling a form in "view" and sending it back to "controller" class.
In my database i want to add the date and time of user creation.
code in my view
<div class="form-group">
#Html.LabelFor(model => model.Ticket_CreationDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ticket_CreationDate)
#Html.ValidationMessageFor(model => model.Ticket_CreationDate)
</div>
</div>
code in controller class
public ActionResult Create([Bind(Include = "Ticket_SenderEmail,Ticket_Sujet,Ticket_Body,Ticket_CreationDate,Ticket_ClientID,Ticket_Priority,Ticket_UserID,Ticket_Status_ID")] Ticket ticket)
{
if (ModelState.IsValid)
{
db.Ticket.Add(ticket);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Ticket_ClientID = new SelectList(db.Client, "Client_Id", "Client_Nom", ticket.Ticket_ClientID);
ViewBag.Ticket_Priority = new SelectList(db.Priority, "Priority_Id", "Priority_Name", ticket.Ticket_Priority);
ViewBag.Ticket_Status_ID = new SelectList(db.Ticket_Status, "Ticket_Status_Id", "Ticket_Status_Nom", ticket.Ticket_Status_ID);
ViewBag.Ticket_UserID = new SelectList(db.User, "User_Id", "User_Nom", ticket.Ticket_UserID);
return View(ticket);
}
My question is how i can send current datetime from view to controller ?
You won't send the date from the view, you will handle that in the controller...
yourdataentity newentity = new yourdataentity();
//the rest of your implementation may be a bit different, but this is one way to set the date for a new record...
newentity.createDate = DateTime.Now;
yourentitys.Add(newentity);
if (ModelState.IsValid)
{
db.yourentitys.Add(newentity);
db.SaveChanges();
}