Create variable in view and assign - asp.net

I need to create a string variable in my View and assign to a hidden input which is bound to a property on my strongly typed model
I guess it is something like
#Html.HiddenFor(m=>m.nodelist, new {#value = myVar})
however not working

Don't try to be setting the #value attribute on the html helper. That's not how those helpers have been designed to work. They have been designed to bind to the value of the corresponding property on the view model you passed to this view.
So it's as simple as:
#Html.HiddenFor(m => m.nodelist)
and in the controller action rendering this view you would assign the corresponding property on the view model to the desired value:
public ActionResult Index()
{
MyViewModel model = ...
model.nodelist = someVariable;
return View(model);
}
If on the other hand this variable is actually a javascript variable then you should obviously use javascript to assign it to the hidden field:
<script type="text/javascript">
var myVar = 'some value';
$('#nodelist').val(myVar);
</script>
or if you are not using jQuery:
<script type="text/javascript">
var myVar = 'some value';
document.getElementById('nodelist').value = myVar;
</script>

use simple html hidden field and keep it's name same as property name.
This works perfectly
#{
string val=myVar;
}
<input type="hidden" name="nodelist" value="#val" />

Is myVar a javascript variable?
You could assign your hidden field an ID property.
#Html.HiddenFor(m=>m.nodelist, new {#id = "hdnNodeList"})
and using javascript or jquery you could do the following
$('#hdnNodeList').val(myVar);
or if myVar is a C# variable you could try the following (this will render an html output, although you could do it here, its better to assign a value to m.nodelist in your controller if possible)
$('#hdnNodeList').val('#myVar');

Related

Insert id into list if checkbox is checked

Net MVC and I have a table with products I want to buy.
I want to use a Checkbox to confirm the purchase.
But how can I insert the ID in a List<int>?
I have a class Approved with an attribute List<int> approve
I tried:
#Html.CheckBoxFor(m.approve.Add(id))
#Html.CheckBoxFor(m=>m.approve.Add(id))
#Html.CheckBoxFor(ViewBag.l.approve.Add(id)
How can that task be done ?
You can easyly bind a list to a model:
Model Binding To A List
So, you simply need to make a list of a class created for this, which includes the integer id, and a boolean to hold the checkbox state, somethign like this:
public class IdState
{
public int Id {get;set;}
public bool Checked {get;set;}
}
The list must be of this class, i.e. List<IdState>
The key is using a syntax like this:
Html.CheckBoxFor(m => m[i].Product)
Which will produce and input whose name is something like this:
name="[0].Product"
Then, the model binder will bind your list automatically. Of course, your post action must recevied a List<IdState> to function properly.
u can use html to insert id to your checkbox
#model yourModel
//for generate checkbox
<input type="checkbox" #(yourmodel ? " checked=checked " : null) name="YourCheckBoxName" value="#model.ID" >
use formCollection for get value in your controller from your view
I solved this problem that way:
This Javascript function walks through all checkboxes and saves the Id of the checked once to an hidden input.
<script>
function submit() {
var x = new Array();
for (i = 0; i < ids.length; i++){
if ($("#" + ids[i].toString() + ".cb").is(':checked')) {
x.push(ids[i]);
}
}
console.log(x.toString());
$("#str").val(x.toString());
}
</script>
After toggling a checkbox the value of the hidden input is refreshed
<script>
$(document).ready(function () {
$("input.cb").change(function () {
submit();
});
});
</script>
Here I create an array with all possible ids to improve simplicity and performance.
Otherwise I had to walk through all possible ids and check them.
<script>ids.push(#id);</script>
This is my checkbox:
<input type="checkbox" value="#id" id="#id" class="cb" />

Getting html select value on postback

I'm having a bit of trouble here, hoping someone can help:
I am dynamically populating an html select element in a razor script and onChange I am hoping to get this posted value.
It is posting back as the page is refreshing but I don't seem to be getting the value of the select; The reason I know is that I am passing a category and filtering on it. This filtering works when I change the querystring in the URL manually and post it.
Razor Script:
#using umbraco.MacroEngines
#inherits DynamicNodeContext
#{
dynamic rootNode = #Model.NodeById(1066);
DynamicNodeList list = rootNode.Descendants();
List<dynamic> categories = new List<dynamic>(list.Cast<dynamic>());
List<string> alias = new List<string> { "GeneralPage" };
var filtered = categories.Where(n => alias.Contains(n.NodeTypeAlias));
}
<form method="post" action="">
<select id="selectCategory" name="selectCategory" onchange="this.form.submit(); alertMe(selectCategory)">
#foreach (var node in filtered)
{
<option value="#node.Name">#node.Name</option>
}
</select>
</form>
<script type="text/javascript">
function alertMe(selectCategory) {
alert(selectCategory)
}
</script>
You'll notice I have a function to alert the selected value but this is coming back as [object HTMLSelectElement]
I can post more code if needed to show what's happening on the server, but as I said the filtering DOES work, however I am trying capture the value in the following way:
string category = Request["selectCategory"];
if (category != null)
{
Any help much appreciated.
Thanks
Try:
ViewContext.RouteData.Values["selectCategory"]
As for the javascript, you are passing in the dom reference to the select list, not the selected item. If you want to see the value of it, you need to use
alert(selectCategory.value)

Passing Querystring data to a Model in ASP.NET MVC 2

I have a strongly typed view inheriting from a POCO class. I want to initialize the property of a model with a Querystring value at the time when view loads.
On the View Load I am using ViewData to the save the code :
public ActionResult Data() {
ViewData["QueryStringValue"] = this.Request.QueryString["Param1"]
return View();
}
In the HTML markup, I am using this code to initialize the model property in a hidden variable
<%:Html.HiddenFor(m=>m.Param,
Convert.ToInt32(Html.Encode(ViewData["QueryStringValue"]))) %>
m.param is a byte type.
URL of the request is somewhat like this : http://TestApp/Data/AddData?Param1=One
On View Save event, I am using model binding but issue is that I don't get to see the value of param initialized in the controller. It is always NULL.
My Save Event maps to a controller :
[HttpPost]
public ActionResult SaveData(MyData d)
{
string paramValue = d.Param; //this always returns null
BO.Save(d);
}
I inspected the HTML source and saw that the value of the hidden field itself is blank. Not sure why this is happening since the below code works and shows the param value in a heading element
<h2> <%=Html.Encode(ViewData["QueryStringValue"]) %> </h2>
I have no idea where I am going wrong on this.
I think, Instead of Passing the Querystring value in ViewData, You should set it as the Property value of your ViewModel/ Model and pass that to your View.
public ActionResult Data()
{
YourViewModel objVm=new YourViewModel();
objVm.Param=Request.QueryString["Param1"];
return View(objVm);
}
Now in your Strongly typed View, use it like this
#model YourViewModel
#using(Html.BeginForm())
{
#html.HiddenFor(#m=>m.Param);
<input type="submit" value="Save" />
}
Now Param value will be available in yout HttpPost action method
[HttpPost]
public ActionResult Data(YourViewModel objVm)
{
string param=objVm.Param;
//Do whatever you want with param
}
Just made this work, Issue is with this line:
<%:Html.HiddenFor(m=>m.Param,
Convert.ToInt32(Html.Encode(ViewData["QueryStringValue"]))) %>. I stated in the question that m.Param is of type byte. I figured out that issue was with casting.
I tried this code and it worked
<%:Html.HiddenFor(m => m.Param, (byte)Convert.ToInt16(this.Request.QueryString["Param1"].ToString()))%>

Validating that a form input is not empty

I have this code for Form Submit..
<input type="submit" runat="server" id="buttonSubmit" value="Add" style="width:100px;" />
My BeginForm is like this..
<% using (Html.BeginForm("Insert", "StudentController", FormMethod.Post, new { #id = "exc-" }))
{%>
I have one textbox in my view I need to check my textbox is empty or not if it is Empty display alert box saying please Enter some value in textbox
other wise go to controler..
Please any body help me out?
thanks
You can do this many ways, but possibly the cleanest is to use Data Annotations on your ViewModel. For example -
public class MyViewModel
{
[Required]
public string MyProperty { get; set; }
}
Now in your View use
<% Html.EnableClientValidation(); %>
just before you start the form. This will cause a JavaScript object to be emitted in the markup sent to the client. The script looks like this example
<script type="text/javascript">
//<![CDATA[
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"FirstName","ReplaceValidationMessageContents":true,"ValidationMessageId":"FirstName_validationMessage","ValidationRules":[{"ErrorMessage":"The First Name field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"LastName","ReplaceValidationMessageContents":false,"ValidationMessageId":"LastName_validationMessage","ValidationRules":[{"ErrorMessage":"The Last Name field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"EmailAddress","ReplaceValidationMessageContents":false,"ValidationMessageId":"EmailAddress_validationMessage","ValidationRules":[{"ErrorMessage":"The Email Address field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"ZipCode","ReplaceValidationMessageContents":false,"ValidationMessageId":"ZipCode_validationMessage","ValidationRules":[{"ErrorMessage":"Zip Code must be 5 character long.","ValidationParameters":{"minimumLength":0,"maximumLength":5},"ValidationType":"stringLength"},{"ErrorMessage":"Zip Code must be five digits.","ValidationParameters":{"pattern":"\\d{5}"},"ValidationType":"regularExpression"},{"ErrorMessage":"The Zip Code field is required.","ValidationParameters":{},"ValidationType":"required"}]}],"FormId":"form0","ReplaceValidationSummary":false,"ValidationSummaryId":"valSumId"});
//]]>
</script>
This object contains validation metadata that can be used by a client side validation plugin to hook up validation on the client side. The plugin that comes with ASP.NET MVC 2 is the Microsoft AJAX validator and you will need to include these scripts in the page to use the validation (MicrosoftAjax.js, MicrosoftMVCAjax.js and MicrosoftMvcValidation.js in that order).
Alternatively, if you're more comfortable with jQuery, you can get a script in the MvcFutures source that hooks the validation into the jQuery validate plugin (this isn't a fully fledged script and is missing a few pieces, such as getting client side validation summaries). The script is MicrosoftMvcJQueryValidation.js and you can get it here
The advantage of using Data Annotations is that you get the server side validation too and your client and server side validation will validate for the expected values. Also, the Data Annotations allow you to set Error Messages and names for the field labels from the attributes (error messages and display names* can also come from resource files)
*Because MVC2 was compiled against .NET 3.5 version of Data Annotations, display name cannot be set from resource files. There is a workaround to this - DisplayName attribute from Resources?.
NOW THE EASY WAY
Just set up a submit event handler on the form
var form = document.getElementById('exc-');
var oldSubmit = form.onsubmit || function() {};
form.onsubmit = function() {
var input = document.getElementById('myinput');
if (input.value === '') {
alert('please Enter some value in textbox');
return false;
}
oldSubmit();
}
or with jQuery
$('#exc-').submit(function() {
if ($('#myinput').val() === '') {
alert('please Enter some value in textbox');
return false;
}
});

How to bind Lists of a custom view model to a dropDownList an get the selected value after POST in ASP.NET MVC?

I have following problem. In my view model I defined some list properties as follows:
public class BasketAndOrderSearchCriteriaViewModel
{
List<KeyValuePair> currencies;
public ICollection<KeyValuePair> Currencies
{
get
{
if (this.currencies == null)
this.currencies = new List<KeyValuePair>();
return this.currencies;
}
}
List<KeyValuePair> deliverMethods;
public ICollection<KeyValuePair> DeliveryMethods
{
get
{
if (this.deliverMethods == null)
this.deliverMethods = new List<KeyValuePair>();
return this.deliverMethods;
}
}
}
This view model is embedded in another view model:
public class BasketAndOrderSearchViewModel
{
public BasketAndOrderSearchCriteriaViewModel Criteria
{
[System.Diagnostics.DebuggerStepThrough]
get { return this.criteria; }
}
}
I use 2 action methods; one is for the GET and the other for POST:
[HttpGet]
public ActionResult Search(BasketAndOrderSearchViewModel model){...}
[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model){...}
In the view I implement the whole view model by using the EditorFor-Html Helper which does not want to automatically display DropDownLists for List properties!
1. Question: How can you let EditorFor display DropDownLists?
Since I could not figure out how to display DropDownLists by using EditorFor, I used the DropDownList Html helper and filled it through the view model as follows:
public IEnumerable<SelectListItem> DeliveryMethodAsSelectListItem()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem()
{
Selected = true,
Text = "<Choose Delivery method>",
Value = "0"
});
foreach (var item in this.DeliveryMethods)
{
list.Add(new SelectListItem()
{
Selected = false,
Text = item.Value,
Value = item.Key
});
}
return list;
}
My 2. question: As you can see I pass my view model to the action metho with POST attribute! Is there a way to get the selected value of a DropDownList get binded to the passed view model? At the moment all the DropDownList are empty and the selected value can only be fetched by the Request.Form which I definitely want to avoid!
I would greatly appreciate some ideas or tips on this!
For those like me that got to this post these days I'd recommend you to fully download the tutorial from http://www.asp.net/mvc/tutorials/mvc-music-store-part-1 which covers this and most of the common techniques related with .NET MVC applications.
Anyway Really usefull your post and answers man (If I could vote you I would :)
Let's try to take on this one:
Answer to Question 1: How can you let EditorFor display DropDownLists?
When you call Html.EditorFor() you can pass extra ViewData values to the EdiorTemplate View:
<%: Html.EditorFor(model => Model.Criteria, new { DeliveryMethods = Model.DeliveryMethods, Currencies = Model.Currencies}) %>
Now you have ViewData["DeliveryMethods"] and ViewData["Currencies"] initialized and available inside your EditorTemplate.
In your EditorTemplate you somehow need to call and convert those entries into DropDowns / SelectLists.
Assuming you've got an ascx file of type System.Web.Mvc.ViewUserControl<BasketAndOrderSearchCriteriaViewModel> you could do the following:
<%: Html.LabelFor(model => model.DeliveryMethods) %>
<%: Html.DropDownList("SelectedDeliveryMethod", new SelectList(ViewData["DeliveryMethods"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedDeliveryMethod)) %>
Same goes for the Currencies.
<%: Html.LabelFor(model => model.Currencies) %>
<%: Html.DropDownList("SelectedCurrency", new SelectList(ViewData["Currencies"] as IEnumerable, "SelectedDeliveryMethod", "Key", "value", Model.SelectedCurrency)) %>
This setup will make your DeliveryMethodAsSelectListItem() obsolete and you can use any kind of list. Means you are not bound to KeyValuePairs. You'll just need to adjust your call on Html.DropDownList() from now on.
As you can see, I have introduced some new properties to your BasketAndOrderSearchCriteriaViewModel:
Model.SelectedDeliveryMethod
Model.SelectedCurrency
They are used to store the currently selected value.
Answer to Question 2: Is there a way to get the selected value of a DropDownList get binded to the passed view model?
In the EditorFor template we are passing the newly created Model.SelectedDeliveryMethod and Model.SelectedCurrency properties as the SelectedValue Parameter (See 4th Overload of the DropDownList Extension Method).
Now that we have the View doing it's job: How can we get the currently selected value inside the POST Action?
This is really easy now:
[HttpPost]
public ActionResult SubmitSearch(BasketAndOrderSearchViewModel model)
{
...
var selectedDeliveryMethod = model.Criteria.SelectedDeliveryMethod;
var selectedCurrency model.Criteria.SelectedDeliveryMethod;
...
}
Note: I don't have an IDE to test it right now, but it should do the trick or at least show you in which direction to go.

Resources