selected item in dropdownlist mvc3 - asp.net-mvc-3

Mvc3 dropdownlistFor is deriving me crazy!!!
I have two selects with the same code (different tevt and values) but one of them not works.
here is my Controller code:
[Authorize(Roles = "admins")]
public ActionResult Edit(int id = -1)
{
Advertise Advertise = db.Advertises.Find(id);
if (null == Advertise)
return View("ProductNotFound");
var selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "A", Value = "A", Selected = ("A" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "B", Value = "B", Selected = ("B" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "C", Value = "C", Selected = ("C" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "D", Value = "D", Selected = ("D" == Advertise.Class) });
ViewBag.Class = new SelectList(selectListItems, "Value", "Text",Advertise.Class);
var selectListItems2 = new List<SelectListItem>();
selectListItems2.Add(new SelectListItem { Text = "Image", Value = "Image", Selected = ("Image" == Advertise.FileType) });
selectListItems2.Add(new SelectListItem { Text = "Flash", Value = "Flash", Selected = ("Flash" == Advertise.FileType) });
ViewBag.Type = new SelectList(selectListItems2, "Value", "Text",Advertise.FileType);
return View(Advertise);
}
and here is my view code:
<tr>
<td class="label">
#Html.LabelFor(model => model.Class) :
</td>
<td class="editor-field">
#Html.DropDownListFor(model => model.Class, (SelectList)ViewBag.Class)
#Html.ValidationMessageFor(model => model.Class)
</td>
</tr>
<tr>
<td class="label">
#Html.LabelFor(model => model.FileType) :
</td>
<td class="editor-field">
#Html.DropDownListFor(model => model.FileType, (SelectList)ViewBag.Type)
#Html.ValidationMessageFor(model => model.FileType)
</td>
</tr>
the secound select works perfectly and the first one (class) doesn't select the selected item on page load.
and for the record, the value stored in the database is C.
please help!!!

What a ...!!!!
I found out the reason of not working select is: the name of my variable (ViewBag.Class) is the same as my Field in the model!!! I change ViewBag.Class to ViewBag.glass (just to change the name) and it worked!!!
thanks anyway.
I hope it helps somebody which has this problem!!!

Related

Sent form (list object) to controller AJAX MVC

I want sent form (list of object) with ajax. But the function serialize() in JS doesnt read in controller
JS File:
function save() {
$.ajax({
url: "/Ocena/AddOcene",
method: "POST",
dataType: "html",
data: {
id: $("#KlasaDDL option:selected").val(),
dodaj: $('#formOceny').serializeArray()
},
success: function (html) {
$('#load').html(html);
}
})
}
$(function () {
var llBtn = $('#saveForm');
llBtn.click(function () {
save();
});
});
In controller I have parametrs:
public ActionResult AddOcene(string id, List<Dodaj_ocene> dodaj)
View:
#model List<biblioteka.Dodaj_ocene>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "formOceny" }))
{
#Html.DropDownListFor(x => Model[0].Przedmiot, (SelectList)ViewBag.Przedmiot, "--Dostępne przedmioty--", new { #class = "form-control" })
#*#Html.DropDownList(m => Model[0].Przedmiot, *#
<p>Wprowadź rodzaj</p>
#Html.TextBoxFor(m => Model[0].Rodzaj, new { #class = "form-control" })
<p>Wprowadź Opis</p>
#Html.TextBoxFor(m => Model[0].Opis, new { #class = "form-control" })
<p>Wybierz wagę ocen:</p>
#Html.DropDownListFor(m => Model[0].Waga, new SelectListItem[] {
new SelectListItem{ Value = "5", Text = "V", Selected = Model[0].Waga == 5 } ,
new SelectListItem{ Value = "4", Text = "IV", Selected = Model[0].Waga == 4 } ,
new SelectListItem{ Value = "3", Text = "III" , Selected =
}, new { #class = "form-control" })
<br /> <br />
<table class="table">
<tr>
</tr>
#for (var index = 0; index < Model.Count; index++)
{
<tr>
<td>#Model[index].ImieNazwisko </td>
<td>
#Html.DropDownListFor(m => Model[index].Wartosc, new SelectListItem[]{
new SelectListItem{ Value = "0", Text = "Brak oceny", Selected = Model[index].Wartosc == 0 } ,
new SelectListItem{ Value = "1", Text = "1" , Selected = Model[index].Wartosc == 1 }
} , new { #class = "form-control" })
</td>
</tr>
}
</table>
<div class="form-group">
<div></div>
<button type="button" class="btn btn-info" id="saveForm">Zapisz</button>
</div>
}
I would be very grateful for a Apparently

Updating TextBoxFor when changing DropDownListFor

I'm using ASP MVC 3 and currently having a problem getting new data in my textboxes when I change the value of my dropdownlistfor.
<div id="BagelProductEdit">
<h2>Bagel</h2>
#Html.DropDownListFor(x => x.SelectedOptionBagel, Model.LstBagelsList, new { #class = "width200", #onchange = "refreshTextBoxFors()" })
<br />
<table>
<tr>
<td>Bagelnaam</td><td> #Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).Name,new { Name ="txtEditBagelName" })</td>
</tr>
<tr>
<td>Vertaling</td><td> #Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).NameFr,new { Name ="txtEditBagelNameFr" })</td>
</tr>
<tr>
<td>Prijs</td>
<td> #Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).Price,new { Name ="txtEditBagelPrice" })</td>
</tr>
</table>
<input class="button widthorderProduct" type="submit" name="BtnEditBagel" value="Edit een bagel" />
</div>
How can I get the refreshed value in my textboxes when the value of my dropdownlist changes?
You can add an ID to that dropdownlist:
#Html.DropDownListFor(x => x.SelectedOptionBagel, Model.LstBagelsList, new { #class = "width200", #onchange = "refreshTextBoxFors()", id= "myDDL" })
Then, in the refreshTextBoxFors() you can access the dropdownlist selected value this way (assuming you are using jQuery):
$("#myDDL").val();
If you need the selected text (not the value):
$("#myDDL :selected").text();
In you are not using jQuery, but plain Javascript, you can use this for getting the selected value in a DropDownList:
var e = document.getElementById("myDDL");
var selValue = e.options[e.selectedIndex].value;
EDIT - To set the data of textboxes:
Once you have the DDL selected value you can do:
if(selValue == '1'){
$('#test').val('here is the value you want to put');
}
else{
$('#test').val('other value');
}
Now, in the example in your comment, it seems you have a list of TextBoxFors. So if you put an id in a loop, it will set that to all of your textboxes. You can put a #class = "test" instead and access the textboxes using $('.test') instead of $('#test').

Drop down box in edit.cshtml

I am creating an ASP.NET MVC 3 application which references a database and within the Edit.cshtml file I wish to limit the edit function of one of the items (Score) to simply be either 0,1,2,3,4. I have tried the options in this post Converting HTML.EditorFor into a drop down (html.dropdownfor?) but cannot seem to get it working.
<div class="editor-label">
#Html.LabelFor(model => model.Score)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Score, "YesNoDropDown")
#Html.ValidationMessageFor(model => model.Score)
</div>
Many thanks.
Chri3
If you don't forsee it needing to be changed often, I'd just use a static select like below:
<div class="editor-label">
#Html.LabelFor(model => model.Score)
</div>
<div class="editor-field">
<select id="score" name="score">
#for(int i=0; i<5; i++){
<option value="#i" #(Model.Score==i ? " selected": "")>#i</option>
}
</select>
</div>
to use Html.DropDownListFor, you need to pass in the argument of type IEnumerable<SelectListItem>.
Here i've created some mockup for you
in Model
public class SampleModel
{
public string SeletectRateItem { get; set; }
public IList<SelectListItem> RateItem
{
get
{
var item = new List<SelectListItem>();
item.Add(new SelectListItem(){Selected = false, Text = "1", Value = "1"});
item.Add(new SelectListItem(){Selected = false, Text = "2", Value = "2"});
item.Add(new SelectListItem(){Selected = false, Text = "3", Value = "3"});
item.Add(new SelectListItem(){Selected = false, Text = "4", Value = "4"});
item.Add(new SelectListItem(){Selected = false, Text = "5", Value = "5"});
return item;
}
}
}
and in cshtml
#Html.DropDownListFor(m => m.SeletectRateItem, Model.RateItem)

How can I have the values from my model match the selected values in my dropdown lists?

How can I have the values from my model match the selected values in my dropdown lists?
What I would like to do is to have the dropdown list reflect the property value of the model. I've only been able to show the same value in all of the dropdown lists. I've been trying to do this:
#Html.DropDownList("searchString", Model.Enrollments.FirstOrDefault().WeekDays.Select(s =>
new SelectListItem { Text = s.ToString(), Value = s.ToString(),
Selected = s.ToString().Equals(Model.Enrollments.FirstOrDefault().classDays) }))
but with no luck.
A snippet of my Enrollment model:
public string[] weekDays = new string[6] { "Day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
public string[] WeekDays
{
get { return weekDays; }
}
My view is of type: #model SchoolIn.Models.Student but I would like to interject another model, Model.Enrollments and minipulate the dropdown list items.
<table>
<tr>
#{
int cnt = 0;
List<SchoolIn.ViewModels.EnrolledCourseData> courses = ViewBag.Courses;
foreach (var course in courses)
{
if (cnt++ % 4 == 0)
{
#: </tr> <tr>
}
#: <td >
<br /><br /><br />
<input type="checkbox"
name="selectedCourses"
value="#course.CourseID"
#(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")))
/>
#*course.CourseID #: #course.Title*#
#course.Title<br /> <br />
if (Model.Enrollments != null)
{
#Html.DropDownList("searchString", Model.Enrollments.FirstOrDefault().WeekDays.Select(s => new SelectListItem { Text = s.ToString(), Value = s.ToString(), Selected = s.ToString().Equals(Model.Enrollments.FirstOrDefault().classDays) }))
}
#:</td>
}
#:</tr>
}
</table>
#Html.DropDownListFor( x => x.courseId, new SelectList(LookupUtils.AvailableCourcesList(), "Value", "Text", Model.courseId))
LookupUtils is a static class have:
public static List<SelectListItem> AvailableCourcesList()
{
var dataContext = new YourDataContext( );
var data = dataContext.GetCourcesFn().ToList();
var result = ( from res in data
select new SelectListItem()
{
Text = res.courseName,
Value = res.courseId.ToString()
} ).ToList();
return result;
}

Refresh portion of the page

I have a page that contains 3 divisions such as General, Attendee Information and Customized Questions (Partial view). The Customized questions will display a list of questions (textbox) along with the answer(dropdownlist) , which contains an edit button to modify the answer field in the dropdownlist. Now, when the edit button was clicked, a pop-up window will appear to modify the answer field, once the user clicked the save button the modified answer should reflects in the dropdownlist. I already created a partial view for Customized Questions but still the answer value didn't reflect the changes in the dropdownlist. Any sample codes or ideas?
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
var eventdetails = _service.GeteventByID(eventid);
return PartialView( "CustomizedQuestions", eventdetails);
}
Partial View
#using EM.Website.Helpers
#model EM.Model.tbl_SBAem_Event
#{
var dropdownList = new List<KeyValuePair<int, string>> {new KeyValuePair<int, string>(0, "Required"), new KeyValuePair<int, string>(1, "Optional"), new KeyValuePair<int, string>(2, "Hidden")};
var selectList = new SelectList(dropdownList, "key", "value", 0);
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<table class="table-customized-question">
<tr>
<th class="td-customized-question-row"></th>
<th class="td-customized-question-row">Question Label</th>
<th class="td-customized-question-row">Display Mode</th>
<th class="td-customized-question-row">Answer Field</th>
<th class="td-customized-question-row">Edit Choices</th>
</tr>
<tr>
<td class="td-customized-question-firstrow">#1</td>
<td class="td-customized-question-row">#Html.EditorFor(model => model.EM_opt1Name)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_reqOpt1, selectList)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_opt1Values, #Html.SplitText(Model.EM_opt1Values, ','), new { #class = "dropdownlist-width" })</td>
<td>#Html.ActionImage("CustomizedQuestion", new { eventID = Model.EventMngID, question = Model.EM_opt1Name }, "~/Content/Images/edit.jpg", "Edit", new { #class = "editButton", title = Model.EM_opt1Name, answers = Model.EM_opt1Values, id = "EM_opt1Values", eventID = Model.EventMngID })</td>
</tr>
<tr>
<td class="td-customized-question-firstrow">#2</td>
<td class="td-customized-question-row">#Html.EditorFor(model => model.EM_opt2Name)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_reqOpt2, selectList)</td>
<td>#Html.ActionImage("CustomizedQuestion", new { eventID = Model.EventMngID, question = Model.EM_opt2Name }, "~/Content/Images/edit.jpg", "Edit", new { #class = "editButton", title = Model.EM_opt2Name, answers = Model.EM_opt2Values, id = "EM_opt2Values", eventID = Model.EventMngID })</td>
</tr>
<tr>
<td class="td-customized-question-firstrow">#3</td>
<td class="td-customized-question-row">#Html.EditorFor(model => model.EM_opt3Name)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_reqOpt3, selectList)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_opt3Values, #Html.SplitText(Model.EM_opt3Values, ','), new { #class = "dropdownlist-width" })</td>
<td>#Html.ActionImage("CustomizedQuestion", new { eventID = Model.EventMngID, question = Model.EM_opt3Name }, "~/Content/Images/edit.jpg", "Edit", new { #class = "editButton", title = Model.EM_opt3Name, answers = Model.EM_opt3Values, id = "EM_opt3Values", eventID = Model.EventMngID })</td>
</tr>
<tr>
<td class="td-customized-question-firstrow">#4</td>
<td class="td-customized-question-row">#Html.EditorFor(model => model.EM_opt4Name)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_reqOpt4, selectList)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_opt4Values, #Html.SplitText(Model.EM_opt4Values, ','), new { #class = "dropdownlist-width" })</td>
<td>#Html.ActionImage("CustomizedQuestion", new { eventID = Model.EventMngID, question = Model.EM_opt4Name }, "~/Content/Images/edit.jpg", "Edit", new { #class = "editButton", title = Model.EM_opt4Name, answers = Model.EM_opt4Values, id = "EM_opt4Values", eventID = Model.EventMngID })</td>
</tr>
<tr>
<td class="td-customized-question-firstrow">#5</td>
<td class="td-customized-question-row">#Html.EditorFor(model => model.EM_opt5Name)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_reqOpt5, selectList)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_opt5Values, #Html.SplitText(Model.EM_opt5Values, ','), new { #class = "dropdownlist-width" })</td>
<td>#Html.ActionImage("CustomizedQuestion", new { eventID = Model.EventMngID, question = Model.EM_opt5Name }, "~/Content/Images/edit.jpg", "Edit", new { #class = "editButton", title = Model.EM_opt5Name, answers = Model.EM_opt5Values, id = "EM_opt5Values", eventID = Model.EventMngID })</td>
</tr>
<tr>
<td class="td-customized-question-firstrow">#6</td>
<td class="td-customized-question-row">#Html.EditorFor(model => model.EM_opt6Name)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_reqOpt6, selectList)</td>
<td class="td-customized-question-row">#Html.DropDownListFor(model => model.EM_opt6Values, #Html.SplitText(Model.EM_opt6Values, ','), new { #class = "dropdownlist-width" })</td>
<td>#Html.ActionImage("CustomizedQuestion", new { eventID = Model.EventMngID, question = Model.EM_opt6Name }, "~/Content/Images/edit.jpg", "Edit", new { #class = "editButton", title = Model.EM_opt6Name, answers = Model.EM_opt6Values, id = "EM_opt6Values", eventID = Model.EventMngID })</td>
</tr>
</table>
}
Jquery-Ajax
$(".editButton").live("click", function (e) {
e.preventDefault();
var $title = $(this).attr("title");
var $answers = $(this).attr("answers");
var $controlid = $(this).attr("id");
var $eventId = $(this).attr("eventID");
dropdownlist($controlid, $title, $answers, $eventId);
});
function dropdownlist(controlid, title, answer, eventid) {
var $answersreplaced = answer.replace(/\,/g, " \r");
var $deleteDialog = $('<div><textarea id="answerlist" rows="10" cols="50">' + $answersreplaced + '</textarea><div><div style="font-size:9px">(To change back to an open answer field, delete all choices above and save)</div>');
$deleteDialog.dialog({
resizable: false,
height: 280,
width: 350,
title: title + " - Edit Choices",
modal: true,
buttons: {
"Save": function () {
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: {
answers: $("#answerlist").val(),
question: title,
controlid: controlid,
eventid: eventid
},
success: function (result) {
$(this).dialog("close");
alert(result);
$("#"+controlid+"").html(data);
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
},
Cancel: function () {
$(this).dialog("close");
}
}
});
};
Do my approach is correct?
Yes, your approach is correct. You could for example use jQuery UI dialog to implement the popup and editing part. The idea is to use AJAX in order to avoid refreshing the whole page but only the portion you are interested in. So the partial that will be shown in the modal dialog will contain a form that will be submitted to a controller action using AJAX and the server will return the partial view with the new information about the questions.
You must use
$.ajax({
type: "POST",
url: '#Url.Action("action", "controller")',
data: "{... parameterd}",
contentType: "application/json; charset=utf-8",
success: function (data) {
.. $("#yourDivID").html(data);
}
});
#using (Ajax.BeginForm("action", "controller", ajaxOptions)) , not
#using (Html.BeginForm())

Resources