Added placeholder text to input element in CSHTML - c#

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 }

Related

asp.net mvc set textbox value from value in url without jquery or javascript

I have a textbox inside a form tag like this:
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #type = "email", #aria_describedby = "emailHelp", #text=Request.QueryString["Email"], #value=Request.QueryString["Email"] })
<label>Email</label>
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger", #style = "float:right;" })
Now here is the trick... I have an url that goes like this:
example.com/Registration?Email=someemail#example.com
Now I'm trying to set the value of my textbox automatically by setting the value like this:
#text=Request.QueryString["Email"], #value=Request.QueryString["Email"]
But this doesn't works... The textbox is still empty after the page is loaded...
And I have looked into the html for example and I can see for example text attribute of my input text tag being set to someemail#example.com
What am I doing wrong here?
Okay I found a way to do it. Turns out this is the valid way to do it:
public ActionResult Registration()
{
var regViewModel = new UserRegistrationViewModel { Email = Request.QueryString["Email"] };
return View(regViewModel);
}

Confused on passing parameter to MVC Partial View?

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.

How to give javascript unique ID in htmleditfor method in .net MVC?

I want to give a unique id to htmleditfor method. I want to add Jquery datepicker in it. Please guide...
#Html.EditorFor(model => model.AdExpiryDate, new { htmlAttributes = new { #class = "form-control", placeholder = "MM/DD/YYYY" } })
Your generated html will look like this
<input type="text" id="AdExpiryDate" value="AdExpiryDate" />
You just need to add following javascript code at bottom of your view
<script>
$('#AdExpiryDate').datepicker();
</script>
As others have said, MVC will automatically add the property name from your model to the id and name attributes on the HTML element. However if you want to specify your own id for the element, just update your htmlAttributes:
#Html.EditorFor(model => model.AdExpiryDate, new { htmlAttributes = new { #class = "form-control", placeholder = "MM/DD/YYYY", id = "ad-expiry-date" } })
Then just update your javascript to target the new id that you added:
<script>
var expireDate = $('#ad-expiry-date').val();
alert(expireDate);
</script>

double and decimal not working

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.

Placeholder in #Html.EditorFor(model => model.Name) in MVC 5

I used [prompt("name")] in Controller and
#Html.EditorFor(model => model.Email,
new {placeholder=ViewData.ModelMetadata.Watermark})`
in view but nothing showed
I also used help of Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?
but nothing happened
I need Placeholder for #EditorFor not for Textbox
Any Help Appreciated
You can write HTML attributes into Html.EditorFor using the following syntax. Make sure you use # before class and placeholder so that the renderer knows this is HTML markup.
#Html.EditorFor(model => model.Email, new {
htmlAttributes = new {
#class = "form-control",
#placeholder = "Email Address"
}
})
EditorFor doesn't accept HtmlAttribut argument you have to use TextBoxFor instead of it ;)
try this:
#Html.TextBoxFor(model => model.Email, new {placeholder=ViewData.ModelMetadata.Watermark})`
Work for me just with TextBoxFor.
#Html.TextBoxFor(model => model.emailContact, new {#placeholder = "Your Placeholder Text" }

Categories