I am having difficulties trying to render a checkBox on my Partial View. Basically, what I want is to render the checkBox based on a value extracted from the database. Please see my code below:
<div class="editor-label">
#Html.LabelFor(model => model.Active)
</div>
<div class="editor-field">
#{if (Model.Active == 'Y')
{ Html.CheckBox("Active", true); }
else
{ Html.CheckBox("Active", true); }
}
</div>
In this code block, I am checking for the value inside the Active field from my model and renders the isChecked property of the checkBox to true or false based on that value.
I have debugged this code and used a breakpoint. I have a value of 'Y' from my database and it did went through the if statement. However, when the form pops up, the checkBox didn't render.
Can someone please help me? Thanks!
I think your main problem may be because you have #{ instead of just # before the if.. try remove that.
also, to make things easier.. create a new property on your view model:
public bool IsActive
{
get { return Active == "Y"; }
}
then on your view, use Html.CheckBoxFor(m=> m.IsActive)
Related
i want to use the same view for create and display the same object.
if the page is called by get method it show you a form for edit the object.
if the page is called by post method it show you the value of the object.
i've already done it by using 2 different view.
and trying with model state.
i want something like
#if(Method =="GET"){
// form for edit.
}
else{
// show data.
}
i've tried
#if (ViewData.ModelState.IsValid)//this is always true
{
#using (Html.BeginForm(FormMethod.Post))
{
#Html.TextBoxFor(m => m.ProductID);
#Html.TextBoxFor(m => m.ProductName);
#Html.TextBoxFor(m => m.ProductDescription);
#Html.TextBoxFor(m => m.ProductPrice);
<input type="submit" value="registra"/>
}
}
else
{
<p>#Model.ProductID</p>
<p>#Model.ProductName</p>
<p>#Model.ProductDescription</p>
<p>#Model.ProductPrice</p>
}
if in the controller i use 2 different views it work well but i cannot use the same view because
if its a post method then the model will not have ID. and you should check it in controller /method level
In View i have following error helper
#Html.ValidationSummary(true)
Which, if some property is not validated, show following html
<div class="validation-summary-errors">
<ul>
<li style="display:none"></li>
</ul>
</div>
I have custom css for this class with red border background and problem is that even no error text is shown to user, red border is still displayed.
Can i somehow prevent showing following error html ? Like
#if (Html.ModelState.ContainsNonPropertyErrors() == true)
{
Html.ValidationSummary(true)
}
// or to check if ModelState Error array contains empty keys, becase these are custom messages.
also, can i somehow check if form was submitted to display successfull message ?
for example
#if (Html.ModelState.FormWasSubmitted() == true)
{
if (Html.ModelState.ContainsNonPropertyErrors() == true)
{
Html.ValidationSummary(true)
} else {
Html.Raw("Operation was successfull.")
}
}
or it is a good practice to have model.successfullMessage property in the ViewModel ? (and in view something like #if(ModelState.IsValid) {#Model.successfullMessage} )
How do you do it ?
Ok i think i have working solution
#if (ViewData.ModelState.Keys.Contains(string.Empty))
{
#Html.ValidationSummary(true)
}
I've following code in razor view. How do I use Kendo Radio button to render the same? Mainly, I'm struggling to assign enum value to radio button value.
#if (Model == declaredEnum.Val1)
{
#Html.RadioButtonFor(l => l, (int)declaredEnum.Val1, new { #checked = "checked" });
}
else
{
#Html.RadioButtonFor(l => l, (int)declaredEnum.Val1);
}
#Html.LabelFor(l => l, "Label")
Edit
Definition of Enum
Public Enum declaredEnum
{
Val1,
Val2
}
There is another radio button with the same code, but it checks for val2. Current logic is working fine. I just need to convert to Kendo control instead of razor.
I realize that this post is very old, but I am working with Kendo UI for the first time and needed to figure this out for myself. The following code snippet creates a radio button group called "name-of-radio-group" from an enum with two values. It defaults the first radio button to checked:
<div class="form-group row">
#Html.Label(Enum.GetNames(typeof(declaredEnum)).ToList()[0], new { #class = "col-sm-2" })
#(Html.Kendo().RadioButtonFor(m => m.declaredEnum).Checked(true).Name(Enum.GetNames(typeof(declaredEnum)).ToList()[0])
.HtmlAttributes(new { #class = "col-sm-1", name = "name-of-radio-group"}))
#Html.Label(Enum.GetNames(typeof(declaredEnum)).ToList()[1], new { #class = "col-sm-2"})
#(Html.Kendo().RadioButtonFor(m => m.declaredEnum).Name(Enum.GetNames(typeof(declaredEnum)).ToList()[1])
.HtmlAttributes(new {#class = "col-sm-1", name = "name-of-radio-group"})
)
</div>
In my example I only had two enum values so I did not feel the need to use a loop, instead I just indexed the enums directly. In case it is not clear to someone the m.declaredEnum represents a property on a strongly typed model where the property name is the same as the name of the enum.
I have an ASP MVC 3 page that will allow users to create a drop down list and dynamically add items to it. For example, this is how the page looks when it first loads.
The information on the left is used to specify what page the drop down list will be located (Navbar Item) and what name we are going to give the drop down list (obviously Drop Down List Name).
The information on the right (Allowed Value and Display Value) will be the specific drop down list items. When the user clicks on the Add Another link, an Ajax call goes to the controller, returns a partial view, which is then appended to the Drop Down Items <fieldset> like so:
The problem is, once the user hit's the Submit button, none of the items make it to the controller.
I'm still relatively new to ASP MVC, so I'm wondering if I'm even going about this the right way. Is this the proper way to dynamically add items to a list?
Here is how this view is originally created in the controller
public ActionResult NewList()
{
List<DropDownValues> drop = new List<DropDownValues>();
drop.Add(new DropDownValues());
return View(drop);
}
A list of type DropDownValues is created and sent to the view, which has this tag at the top
#model IEnumerable<Monet.Models.DropDownValues>
The Ajax call below
<script>
$(document).ready(function () {
$("#addItem").click(function () {
if ($('#Field').text() != "" && $('#DisplayPage').text() != "") {
$.ajax({
url: '#Url.Action("BlankDropDownItem", "DropDownValues")',
data: { field: $('#Field').val(), displayPage: $('#DisplayPage').val() },
dataType: 'html',
cache: false,
success: function (html) {
$("#items").append(html);
}
});
} else {
alert("Please enter a Drop Down List Name and Navbar Item first!");
}
return false;
});
});
</script>
calls this controller method
public ActionResult BlankDropDownItem(string field, string displayPage)
{
DropDownValues partial = new DropDownValues();
partial.Field = field;
partial.DisplayPage = displayPage;
return PartialView("DropDownItemPartial", partial);
}
which then appends this Partial View to the main page
#model Monet.Models.DropDownValues
#Html.HiddenFor(model => model.Field)
#Html.HiddenFor(model => model.DisplayPage)
<div class="editor-label">
#Html.LabelFor(model => model.AllowedValue)
</div>
<div class="label-field">
#Html.EditorFor(model => model.AllowedValue)
#Html.ValidationMessageFor(model => model.AllowedValue)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DisplayValue)
</div>
<div class="label-field">
#Html.EditorFor(model => model.DisplayValue)
#Html.ValidationMessageFor(model => model.DisplayValue)
</div>
I'm trying to use the hidden fields in order to make sure all the new items are stored in the database with the correct Field and Navbar Item values (again, not sure if this is the proper way to go about this).
Any advice/suggestions would be greatly appreciated. Thx!
You could use Steven Sanderson's BeginCollectionItem helper to help you out: http://nuget.org/packages/BeginCollectionItem/
His blog post explains the principle using the WebForms view engine but it's just as applicable to Razor: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
If you want to read about the nuts and bolts involved in submitting collections of input fields with the same name, then have a read of Haack's blog post here: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Hope this gives you some pointers!
Following Brad Wilson's excellent series on using and customizing editor templates, I tried adding an Object.cshtml to the Shared\EditorTemplates folder. The template renders, but the [HiddenInput(DisplayValue = false)] on a model property doesn't render a hidden <input type="hidden" ... /> as expected. Using [HiddenInput(DisplayValue = true)] renders both the hidden and visible elements as expected.
I have verified that the default template for Object works fine and renders the hidden inputs. It's only a problem when building a custom template based on Brad's series above.
Looks like something has changed. Inspecting the MVC 3 source, I found that prop.HideSurroundingHtml is used to determine when to print the surrounding HTML, not to print only the hidden element. The following template allows several levels of rendering an editor for an object graph:
#if (ViewData.TemplateInfo.TemplateDepth > 2)
{
#(ViewData.ModelMetadata.Model != null ?
ViewData.ModelMetadata.SimpleDisplayText :
ViewData.ModelMetadata.NullDisplayText)
}
else
{
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm)))
{
if (!prop.HideSurroundingHtml)
{
if (!String.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString()))
{
<div class="editor-label">#Html.Label(prop.PropertyName)</div>
}
#Html.Raw("<div class=\"editor-field\">")
}
#Html.Editor(prop.PropertyName)
if (!prop.HideSurroundingHtml)
{
#Html.ValidationMessage(prop.PropertyName, "*")
#Html.Raw("</div>")
}
}
}
I tidied my version of that up a bit for anyone who cares:
#foreach (var modelMetadata in ViewData.ModelMetadata.Properties)
{
if (modelMetadata.HideSurroundingHtml == false)
{
if (!string.IsNullOrEmpty(Html.Label(modelMetadata.PropertyName).ToHtmlString()))
{
<div class="editor-label">
#Html.Label(modelMetadata.PropertyName)
</div>
}
<div class="editor-field">
#Html.Editor(modelMetadata.PropertyName)
</div>
}
}