asp mvc dropdown list default value does not bound - asp.net-mvc-4

in controller I have :
ViewBag.ActivityTypeID = new SelectList(activityTypes, "ActivityTypeID","Name"
,workFlowDetail.ActivityTypeID);
and in view :
#Html.DropDownListFor(model => model.ActivityTypeID,new SelectList(ViewBag.ActivityTypeID,"Value","Text"), String.Empty)
#Html.ValidationMessageFor(model => model.ActivityTypeID)
The default value which is (workFlowDetail.ActivityTypeID) does not selected by dropdown in my edit view
how can I do that?
thanks

This Problem generally occurs in MVC because model.ActivityTypeID and ViewBag.ActivityTypeID have ActivityTypeID in common that is why problem occur,just change Viewbag name and problem will be resolved..
This will work :-
Controller :
ViewBag.ActivityType = new SelectList(activityTypes, "ActivityTypeID","Name"
,workFlowDetail.ActivityTypeID);
View :
#Html.DropDownListFor(model => model.ActivityTypeID,new SelectList(ViewBag.ActivityType,"Value","Text"), String.Empty)
#Html.ValidationMessageFor(model => model.ActivityTypeID)

Just use the following in your view:
#Html.DropDownList("ActivityTypeID", ViewBag.ActivityTypeID as SelectList)
#Html.ValidationMessageFor(model=>model.ActivityTypeID)

Related

ASP.NET MVC5 setting dropdown list value within a loop on the View

I have a collection that I populate in the controller MenuitemDetails and this populates a property on the view model.
The collection has 3 properties and multiple records
Id, Title and State
State is an integer value which relates to a dropdown list selected value.
The viewmodel also contains a selectList property (stateList) which is used to populate the dropdownlist items on the view.
I'm trying to repopulate the form for an edit action - with the same dropdown item selections
<table>
#for (int counter = 0; counter < Model.MenuitemDetails.Count; counter++)
{
<tr>
<td>
#Model.MenuitemDetails[counter].Title
#Html.DropDownListFor(i => Model.MenuitemDetails[counter].state, Model.stateList)
</td>
<hr />
</tr>
}
</table>
I can't seem to get the values of the dropdown to display the appropriate values selected.
Rather than pass in a select list in the viewmodel it can be created in the razor view and in this way you can use the overload for creating the select list to determine the value to bind.
In the example I am using telerik mvc dropdown list but the same applies in terms of creating the selectList in the razor and with a property to bind to which will determine its state.
#(Html.Kendo().DropDownListFor(m => m.Entity.ProductId)
.DataTextField("Text")
.DataValueField("Value")
.Filter("contains")
.HtmlAttributes(new { #class = "form-control" })
.BindTo(new SelectList(Model.Products, "Id", "FullName", Model.Entity.ProductId)))
You can also try to use an editortemplate for this sort of things like so:
#(Html.Kendo().DropDownListFor(m => m)
.OptionLabel("--Select Value--")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("MethodName", "ControllerName").Data("dataforMethod");
});
})
.Enable(true)
.AutoBind(true)
)
In the .Data() part on the read you dont need to use it only if you have some parameters you need int the funtion to get the dataset

Set optionlabel for Kendo dropdownlist conditionally

I have a Kendo dropdownlist like below:
#(Html.Kendo().DropDownListFor(m => m.Country_ID)
.Name("Country_ID")
.DataTextField("COUNTRY_NAME")
.DataValueField("COUNTRY_CODE")
.OptionLabel("Select Country")
.DataSource(source => source.Read(read => read.Action("GetCountry", "Test")).ServerFiltering(true))
)
I need to change the option label text based on when a ID present in viewbag. Can anyone help me with this?

Multiple radio button groups in MVC 4 Razor

I need to have multiple radio button groups in my form like this:
I know it's simply done by specifying the same "name" html attribute for each group.
HOWEVER
MVC doesn't let you specify your own name attribute when using html helper like this:
#Html.RadioButtonFor(i => item.id, item.SelectedID, new { Name = item.OptServiceCatId })
Because it looks at each tag's "name" attribute (not "id") to map/bind the form to the model which the controller receives, etc.
Some said that specifying each with the same "GroupName" attribute will solve the problem, but it didn't work either.
So, is there any way which works ?
EDIT:
Here's my view (simplified):
#model Service_Provider.ViewModels.SelectOptServicesForSubServiceViewModel
#foreach (var cat in Model.OptServices)
{
//A piece of code & html here
#foreach (var item in cat.OptItems.Where(i => i.MultiSelect == false))
{
#Html.RadioButtonFor(i => item.id, item.SelectedID, new { GroupName = item.OptServiceCatId })
<br />
}
}
NOTE:
My model is a List<OptServices>:
public List<OptServices> Cats {get; set;}
And OptServices has a List of OptItems inside:
public class OptServices
{
//a few things
public List<OptItems> Items {get; set;}
}
all you need is to tie the group to a different item in your model
#Html.RadioButtonFor(x => x.Field1, "Milk")
#Html.RadioButtonFor(x => x.Field1, "Butter")
#Html.RadioButtonFor(x => x.Field2, "Water")
#Html.RadioButtonFor(x => x.Field2, "Beer")
Ok here's how I fixed this
My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.
Here's the final 'working' pseudo-code:
#foreach (var cat in Model.Categories)
{
//A piece of code & html here
#foreach (var item in cat.SubCategories)
{
#Html.RadioButton(item.CategoryID.ToString(), item.ID)
}
}
The result is:
<input name="127" type="radio" value="110">
Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.
Thanks to all of the people who helped me solve this ;)
I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.
The code below was simplyfied.
List<SelectListItem> items = new List<SelectListItem>();
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");
foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
{
items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });
}
ViewBag.TiposPost = new SelectList(items, "Value", "Text");
In the View, I used a foreach to build a radiobutton.
<div class="form-group">
<div class="col-sm-10">
#foreach (var item in (SelectList)ViewBag.TiposPost)
{
#Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
<label class="control-label">#item.Text</label>
}
</div>
</div>
Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.
Hope it's useful!
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
#Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
#Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
You can use Dictonary to map
Assume Milk,Butter,Chesse are group A (ListA)
Water,Beer,Wine are group B
Dictonary<string,List<string>>) dataMap;
dataMap.add("A",ListA);
dataMap.add("B",ListB);
At View , you can foreach Keys in dataMap and process your action

How to display values in a Kendo UI Grid custom popup template

I have a MVC View with a simple Kendo UI Grid:
#(Html.Kendo().Grid(Model.Positions)
.Name("Test")
.Columns(columns =>
{
columns.Bound(p => p.Name);
columns.Command(command => { command.Edit(); });
})
.Editable(ed=>ed.Mode(GridEditMode.PopUp).TemplateName("Position").Window(w => w.Width(600)).Window(w => w.Title("Byrå")))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Model(model => model.Id(p => p.Id))
.Update(update => update.Action("Update", "Office"))
.Read(read => read.Action("Get", "Office")
)
)
)
Under Shared/EditorTemplate I have added Postion.cshtml under Shared/EditorTemplates. The edit open as it shoulds and everything is fine if I use for example:
#Html.TextBoxFor(model => model.Name)
However, I can't use LabelFor since that will display the name of the property and not the value. It also seems like the grid instantiate the popup together with the grid. The values in TextBoxFor is updated when I click on Edit, but if I use #Model.Name it does not. It will always be empty.
I also tried and hide some fields depending on the value of one of the fields, but since I can't use #Model it wont work.
Anyone know how to get around this?
One of Kendo's answers to me was something like this. I haven't got it to work in my case yet, but it might help you. If you came up with a different solution to this issue could you share it?
In you custom editor.
text/javascript
function sendName() {
var grid = $('.k-grid').data().kendoGrid;
var tr = grid.tbody.find('.k-grid-edit-row');
var model = grid.dataItem(tr);
var result = {
name: model.Name
};
return result;
}
They are inspecting the html and assigning first the grid, then the selected row of the grid then mapping the fields of the row to the columns of the Grid.

Change id attribute of an html.editorfor helper in MVC4 with Razor

I have looked through some various answers related to this but all were for mvc3 or not for Razor.
I have a single page that has multiple forms, in partial views, that are for editing a different models. However, most of those models have a 'name' field. I am looking to be able to specify an editorfor with a specific id as such:
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name, new {id = "PersonName"})
#Html.ValidationMessageFor(model => model.Name)
</div>
I have tried various other things but have not found a satisfactory way to handle this. The two choices I seem to have are:
1) Create a form manually using the normal html helpers and construct the model in the controller
2) Rename all the fields in the model to fit the format
Neither of these are exciting to me so I am hoping for an alternative but am afraid that the id is what is used when binding the form to a model.
I realise this is somewhat late but I just ran into this problem myself... I thought "there has to be a way to use the EditorFor and still override the ID"... there is. Do the following and your input has an ID and Name of whatever you like.
#Html.EditorFor(model => model.myField, null, "txtMyField")
Hope this helps and hope it helps other people too.
Note: from what I understand, the reason this is typically not done is to avoid other, dynamically created controls ID's and Names from conflicting.
Change your helper from EditorFor to TextBoxFor the EditorFor, doesn't have a overload to override html properties
Change this
#Html.EditorFor(model => model.Name, new {id = "PersonName"})
To this
#Html.TextBoxFor(model => model.Name, new {id = "PersonName"})
Based on bob's comment :
EditorFor #Html.EditorFor(model => model.FieldName, new { htmlAttributes = new { id = "myuniqueid"} })
Credits to Bob.
Alternatively you can add htmlAttributes
#Html.EditorFor(Model => Model.myField, new { htmlAttributes = new { #class = "form-control", #id = "txtMyField" } })