I have a button that when clicked, will change the value of the variable _name. But this doesn't work when I click Change Name then Refresh.
View
#{
var _name = ViewContext.RouteData.Values["name"].ToString();
}
<div>
<h1>Hello, #name!</h1>
<button type="button" onclick="#(_name = "John Doe")">Change Name</button>
<button type="button" onclick="location.href = '#Url.Action("MyAction", new { name = _name })'">Refresh</button>
</div>
Controller
public ActionResult MyAction(string name = "default") {
ControllerContext.RouteData.Values["name"] = name;
return View;
}
On refresh, the h1 should say "Hello, John Doe!". What is the right way of setting a variable inside HTML using Razor?
I think you are going in wrong direction. do this
put the name in a property in your model
create a hidden with Html.HiddenFor for name
change the value of hidden field with javascript on onClick
when the form is posted you have the new value of name in your model and you don't need new { name = _name } any more
instead of having name in your model and hiddenfor you can use this as alternative
Html.Hidden("name", ViewData("name"))
then for your link make url by this hidden value
Also using RouteData is not a good idea for your purpose, I would recommend to use ViewData["xxx"] instead
Related
So I have this form with this inside it
<div class="form-group">
#*<div class="form-check form-check-box">
#for (int i = 0; i < Model.Features.Count; i++)
{
<div class="form-check form-check-box">
<input class="form-check-input" type="checkbox" asp-for="#Model.Features[i].Selected" value="#Model.Features[i].Text">
<label class="form-check-label" asp-for="#Model.Features[i].Text">#Model.Features[i].Text</label>
</div>
}
</div>
And when I post the form and inspect the properties of the SelectedListItem it looks like this
Even though the Selected should be True because I checked it. Everything else that's in the form gets posted fine, like the text input binds just fine to the string Text property inside my ProductModel, I believe the issue is with the way I'm using the checkbox element properties.
So I can see the checkboxes, and I can check them, etc, but when I post the form, nothing related to the checkboxes applies to the ProductModel
public class ProductModel
{
public string Title { get; set; }
public IList<SelectListItem> Features { get; set; }
}
This is how I show set the Model for the view
public IActionResult PostAd()
{
var model = new ProductModel
{
Features = new List<SelectListItem>()
{
new SelectListItem { Text = "Camera", Value = "Camera" },
new SelectListItem { Text = "Touch Screen", Value = "Touch Screen" }
}
};
return View(model);
}
How do I properly use checkboxes so that when I post the form, the data comes through to the model?
This is the action that gets fired when posting
[HttpPost]
public IActionResult CreateAd(ProductModel Product)
{
return View("Index");
}
The problem you are having is that when the form is posted, ASP.NET will bind the posted data to your model, but only input values within the form are posted. The reason your SelectListItem has null Text and Value properties is because these values are not being posted in the form. The form would need to contain an input (such as a hidden input) for #Model.Features[i].Text and another for #Model.Features[i].Value for these to be bound back to the SelectListItem during model binding because it is the input's name that binds it to a model property. But keep in mind, receiving these from even hidden inputs would enable a user to change them to any value they want so you would need to validate on the server side that they are 1) valid values and 2) allowed to be selected.
Given that fact, I find it makes more sense to simply reload the list of available options, in your case Features, in your HttpPost action, then update that rebuilt list with the user's submitted selections.
Now the only problem left is you're not even getting Selected set to true. This is again, because it's based on the input's (the checkbox's) value. asp-for="#Model.Features[i].Selected" will give the checkbox the name it needs to bind back to that property, and will bind its value attribute to the value of Selected. However, you then also define your own value attribute as value="#Model.Features[i].Text" which overrides the one that would've been generated by the asp-for helper. So when your form is submitted, the model binder tries to bind "Camera" to the boolean Selected property which can't be done so it just gets it's default false value. Generally, a SelectListItem is used for a dropdown (<select>) input. There's no reason you can't use it for this purpose, but you could also just use your own model type for the checkboxes.
I have a checkbox as follows:
#using (Html.BeginForm("ItemsEdit", "Items", FormMethod.Post))
{
#Html.CheckBox("itemCheck")
}
I want to be able to send an additional value to a controller when it is clicked, similar to something like this:
<input id = "#dataLineItem.Split(Model.ItemList.delimiterChar)[0]" type="checkbox" value="true" name="Remember" onclick="sendCheckId(this.id)" />
Below is the jQuery i am using to pass this id value to my controller:
function sendCheckId(checkedId) {
var sentId = checkedId;
$.post("/Items/ItemsEdit/", { sendIdToAction: sentId })
}
However, if i were to use the method above, i wouldnt know how to pass the 'true/false' values of the checkbox, to the same controller.
Maybe try onclick="sendCheckId(this.id,this.value)"
I'm not sure what that sendCheckId function leads to, but it should be pretty quick and easy to expand it to include the second value.
I found out that i could simply do this using the Razor engine:
#Html.CheckBox("itemCheck", new
{
onclick = "alert('Hello')"
}
Credit: https://www.c-sharpcorner.com/forums/how-to-call-on-click-event-in-mvc-5
(The answer by Ramesh Palanivel)
I want to create a button so as to update a label's text after 'onclick'. I found some solutions achieved by using ASPX but I want to use Razor.
//The following is achieved by ASPX
//View
<asp:label id="myLabel" runat="server" />
//Onclick event
myLabel.Text = "my text";
How to do this with Razor view engine in ASP.net MVC?
Are you coming from a asp.net webforms background?
You should update the text with javascript. The runat="server" doesn't exist anymore and shouldn't be used according to MVC principles.
You can have a property in your model like:
ControllerNameModel
{
...
public string LabelText {get; set;} = "my text"; //my text is the default value
}
Then in your Controller you can change the Label Text:
public IActionResult ControllerName(ControllerNameModel model)
{
model.LabelText = "new text for label"
return View(model); // return the view with modified model
}
And in your view you should have your label like this:
<label for="something">#Model.LabelText</label>
P.S.: Change ControllerName to the appropriate name of your controller
You can use a simple ViewBag to do this. Set the value in the controller:
public ActionResult Index()
{
ViewBag.MyCustomTitle = "Title"
return View();
}
... and in the view use it like this:
<label>#ViewBag.MyCustomTitle</label>
I want to use the string in "linktext" and pass it as a parameter into #Html.ActionLink. The reason I want to do this is to retrieve an object from my model
Example code in razor view:
#Html.ActionLink("One","MyAction","MyController",myDictionary[<myLinktextString>],null)
Basically I want myLinktextString to be "One" when I click the actionlink.
an example with a text field and a button click would be something like this
<input type="text" class="linkText" />
<input type="button" class="redirectLink" value="Redirect" />
in your script you would have
$('.redirectLink').on('click', function(){
var url = '#Url.Action("Action", "Controller", new { text = "0000" }';
url = url.replace("0000", $(".linkText").val());
window.location = url;
});
on the button click it will take the value of the text box and add it to a link and in this example redirect the user to that page. Let me know if you have any questions.
I have created a function for doing on validations on textbox entered value based on selection in drop downlist .. ..suppose If the dropdownlist selected item is amount then the entered value in textbox must be in between 10 t0 20 like this i have got two more validations.. for that purpose, I have got one textbox and one dropdwonlist and one button in my view
when i enter value in textbox as 30 and select the drop downlist item as "Amount" and then click on the submit button, the view is not showing any error message and ( if i left textbox as empty and then press submit button its should show error msg but its not showing) (I have written Custom functions for validating these ones on server side)
I have put a breakpoint at a postValues method but its not hitting ...
for that I have done like this (controller part)
public class CrossFieldsTxtboxesController : Controller
{
public ActionResult Index()
{
var itemsforDropdown = new List<SelectListItem> {
new SelectListItem{ Text = "Amount" , Value = "Amount"},
new SelectListItem{Text= "Pound", Value ="Pound"},
new SelectListItem {Text ="Percent", Value ="percent"}
};
ViewData["Listitems"] = itemsforDropdown;
return View("DdlCrossFields");
}
[HttpPost]
public ActionResult PostValues(CrossFieldValidation model)
{
if (!ModelState.IsValid)
{
return View(model);
}
else
{
return RedirectToAction("DdlCrossFields");
}
}
}
and this is my view part
#model MvcSampleApplication.Models.CrossFieldValidation
#{
ViewBag.Title = "DdlCrossFields";
}
<h2>DdlCrossFields</h2>
#using (Html.BeginForm())
{
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownList("Listitems",ViewData["Listitems"] as SelectList)
<input id="PostValues" type="Submit" value="PostValues" />
}
and this is my model part
public class CrossFieldValidation
{
public string DDlList1
{ get; set; }
[Required(ErrorMessage = "Quantity is required")]
[Display(Name= "Quantity:")]
[ValueMustbeInRange]
[NumericAttributes]
public string TxtCrossField
{ get; set; }
}
would any one have any idea why its not working for button click , any suggestions also would be grateful
many thanks..
I don't see any place where you specify an action that should handle POST request (PostValues in your case). You can use an overload of Html.BeginForm and specify POST action name explicitly:
Html.BeginForm("PostValues", "CrossFieldsTxtboxes")
If I'm right, your POST requests go to Index action and therefore ModelState.IsValid is not checked there.
You can use client side validation using jQuery Unobtrusive validation plugin. Please check if you have the following keys in your web.config file:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
But note that custom validation attributes require additional JavaScript code to work on client.
I dont see where you are actually calling the method when you do the post - do you have a javscript click handler?
You need to have the method and controller you want to go to in your Html.BeginForm() or you can have something like the below in your view:
#Html.ActionLink("Post Values", "PostValues", "CrossFieldsTxtboxesController", null, new { #class = "postValuesButton", onclick = "return false;" })