I have a report that shows a list with the following columns:
A key column
A dropdown list showing a list of possible status
A title
This is the razor code:
#foreach (AdminSummary adminSummary in #Model.AdminSummaries) {
index++;
<div class="rep_tr0">
<div class="rep_td0" id="rk_#(index)">#adminSummary.RowKey</div>
<div class="rep_td0">Edit</div>
<div class="rep_td0">Delete</div>
<div class="rep_td0">#Html.DropDownListFor(??, ??)</div>
</div>
}
I also have the following class:
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptions()
{
return new[]
{
new SelectListItem { Value = "1", Text = "Released" },
new SelectListItem { Value = "2", Text = "Review" },
new SelectListItem { Value = "3", Text = "New" }
};
}
}
What I am not sure is how I can link these up. I know in the model I can store the list of
status options something like this:
vm.StatusList = GetAdminStatusOptions();
But how can I create the dropdownlist. I am very confused with all of the options of DropDownList and
DropDownListFor. Which should I be using and how can I send in the list of statuses?
What I am not sure is how I can link these up.
This will depend on how the model looks like.
But here's what you could do:
#for (var index = 0; index < Model.AdminSummaries.Count; index++)
{
<div class="rep_tr0">
<div class="rep_td0" id="rk_#(index)">
#Model.AdminSummaries[index].RowKey
</div>
<div class="rep_td0">
#Html.DropDownListFor(
x => x.AdminSummaries[index].Status,
AdminStatusReference.GetAdminStatusOptions()
)
</div>
<div class="rep_td0">
#Model.AdminSummaries[index].Title
</div>
</div>
}
Related
I've a model that contains 3 tables in my view.
public class InExam
{
public AutoTests TheTest { get; set; }
public List<InTest> TheQuestions { get; set; }
public IEnumerable<Result> SingleQuee { get; set; }
}
First one made to get the detailed page, like "admin/AutoTests/id"
Second one made to get a list of questions linked to the page
Third one is to save radio button strings to post it back into the controller
my plan is to get (say) 20 questions that are linked with the detailed page, Adding 4 radio buttons for each question, and post back every selected button to the controller.
my view form :
#using (Html.BeginForm("Test", "Exams", new { id = Model.TheTest.id }, FormMethod.Post))
{
foreach (var item in Model.TheQuestions)
{
Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();
<div class="container" style="padding-top:50px;direction:rtl;">
<h4 style="text-align:right;font-weight:bold;">#item.Question</h4>
<div class="container">
<div class="row" style="direction:rtl;">
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "1" })
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "2" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer2</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "3" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer3</h5>
</div>
</div>
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
#Html.RadioButtonFor(x => singleQuee.Question, new { #class = "form-control dot", #Name = singleQuee.Question, #Value = "4" })
<h5 style="padding-top:3px;padding-right:8px;">#item.Answer4</h5>
</div>
</div>
#Html.HiddenFor(m => singleQuee.Question)
</div>
</div>
</div>
}
<button class="btn botton" type="submit" onclick="return confirm('');">END</button>
}
i used this line "Kafo.Models.Result singleQuee = Model.SingleQuee.Where(x => x.Question == item.Question).FirstOrDefault();" in my view because i can't use tuple foreach ( C# ver. 5 )
This is my controller code :
[HttpGet]public ActionResult Test(int? id)
{
using (KafoEntities db = new KafoEntities())
{
InExam model = new InExam();
model.TheTest = db.AutoTests.Where(x => x.id == id).FirstOrDefault();
model.TheQuestions = db.InTest.Where(x => x.UserEmail == currentUser.Email && x.ExamId == model.TheTest.id).OrderByDescending(x => x.id).Take(Convert.ToInt32(model.TheTest.QuestionsNumber)).ToList();
model.SingleQuee = db.Result.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Test(int? id, List<Result> singleQuee)
{
using (KafoEntities db = new KafoEntities())
{
int result = 0;
foreach (Result item in singleQuee)
{
Result sets = db.Result.Where(x => x.id == item.id).FirstOrDefault();
sets.Question = item.Question;
db.SaveChanges();
var check = db.InTest.Where(x => x.Question == item.Question).FirstOrDefault();
if (check != null)
{
if (item.Question == "1")
{
result++;
}
}
}
return RedirectToAction("Results", "Exams", new { Controller = "Exams", Action = "Results", id = done.id });
}
}
I first save the new string that came from the radio button value into the result record, then i call it back in the if condition to check it's value
The problem here is i get a
Object reference not set to an instance of an object.
when i post the test, it means that the list is empty, so i need to know what makes the radio buttons not working,
Thanks.
If you want to bind a List of object in Mvc, you should name the controller like "ModelName[indx].PropertyName". In your case it should be "singleQuee[0].Question".
Code Sample
var Indx = 0;
foreach (var item in Model.TheQuestions)
{
.....
var radioName = $"singleQuee[{Indx}].Question";
<div class="col-lg-7" style="text-align:right;margin-right:10px;">
<div class="row">
<input type="radio" name="#radioName" value="1" />
<h5 style="padding-top:3px;padding-right:8px;">#item.RightAnswer</h5>
</div>
</div>
.....
}
Action Method
I have a problem with a partial view. The first time when it is rendered everything is ok, but after that some data is loosed.
This is how my page should look: this is when the partial view is rendered the first time
but when I'm clicking on a category to check his subcategories, the image is null, it is not visible anymore. (only the name is visible)
This is my partial view:
#model IEnumerable<OnlineCarStore.Models.CategoriesVM>
<div class="container">
<div class="row">
#using (Html.BeginForm("SubCategories", "Product"))
{
<div class="list-group col-sm-3" style="width:280px;">
#{var selected = string.Empty;
if (#HttpContext.Current.Session["selectedCar"] == null)
{
selected = string.Empty;
}
else
{
selected = #HttpContext.Current.Session["selectedCar"].ToString();
}
foreach (var c in Model)
{
<a href="#Url.Action("SubCategories", "Product", new { selected = #selected, id = #c.ID, category = #c.CategoryName })" class="list-group-item">
<span> #c.CategoryName</span>
</a>
}
}
</div>
<div class="col-sm-9">
#foreach (var c in Model)
{
<div class="card-group" style="width:200px; display: inline-block">
<div class="card card">
<a href="#Url.Action("SubCategories", "Product", new { selected = #HttpContext.Current.Session["selectedCar"].ToString(), id = #c.ID, category = #c.CategoryName })" id="linkOnImg" class="card-group">
<img class="card-img-top center-block" src="#string.Format("../content/images/categories/{0}.jpg", #c.AtpID)" alt=#c.CategoryName style="padding-top: 5px">
<div class="card-text text-center">
<p class="category-card-title ">
<span class="text-muted">#c.CategoryName</span>
</p>
</div>
</a>
</div>
</div>
}
</div>
}
</div>
and this is the Subcategoris view, where the partial view is rendered second time:
<div class="container">
<div class="row">
#Html.Partial("/Views/Home/CategorieTypes.cshtml");
Here is the Product controller Subcategories method:
public ActionResult SubCategories(string selected, int id, string category)
{
List<CategoriesVM> listOfCategories = new List<CategoriesVM>();
var list = db.Categories.ToList();
var root = list.GenerateTree(c => c.ID, c => c.ParentId).ToList();
TreeItem<Categories> found = null;
var test = new TreeItem<Categories>();
foreach (var rootNode in root)
{
found = TreeGenerator.Find(rootNode, (n) => n.Item.ID == id);
if (found != default(TreeItem<Categories>))
{
test = found;
break;
}
}
foreach (var item in found.Children.ToList())
{
CategoriesVM categoryv = new CategoriesVM();
categoryv.ID = item.Item.ID;
categoryv.AtpID = item.Item.AtpID;
categoryv.Childrens = item.Children.ToList();
categoryv.CategoryName = item.Item.AtpName;//.Name;
listOfCategories.Add(categoryv);
}
SiteMaps.Current.CurrentNode.Title = selected + " " + category;
var tests = found.Children.ToList();
if (found.Children.ToList().Count == 0 )
{
return View("Index");
}
else
{
return View("SubCategories", listOfCategories);
}
}
I've checked in developer tool if the source for the image is correct, and although it is correct, the image is not showed:
Can you please help me in this problem? What I do wrong? Why the images don't appear after the first render of the partial view? Thanks in advance!
The path of the partial view is /Views/Home/CategorieTypes.cshtml and the path of the images is /Content/images/categories. In the partial view you are using ../content/images/categories/ as the path of the images which means that it will search for the path /Views/Content/Images/Categories which is invalid.
Remove the two dots in the src property and add a ~ so it will be like: ~/Content/Images/Categories/{img}.
or
Add one more ../ in order to go one level down to the directory like:
../../Content/Images/Categories/{img}
I am learning MVC and am stuck at this. I was trying to create a filter for name, category, type, Min Value, Max value but when redirected to another view it only shows three parameters but without other values.
Controller (DetailController)
public ActionResult FilteredResult(string searchedLocation, string Type, string PCName, string MinValue, string MaxValue)
{
var A = searchedLocation;
var B = Type;
var C = PCName;
var D = MinValue;
var E = MaxValue;
return View();
}
View
#using (Html.BeginForm("FilteredResult", "Detail", FormMethod.Get))
{
<form>
<h4 style="color: #ed145b;">Find the right property for you</h4>
<ul class="form-style-1">
<li>
#Html.TextBox("Location", ViewBag.Location as string , new { #class = "field-long" })
</li>
<li>
#Html.DropDownList("Type", (SelectList)ViewBag.TypeList, "Select" , new { #class = "field-select" })
</li>
<li>
#Html.DropDownList("Category", (SelectList)ViewBag.CategoryList, "Select" ,new { #class = "field-select" })
</li>
<li>
<label for="amount">Price range:</label>
<input type="text" id="amount" class="field-long" readonly style="border:0; color:#ee2265; font-weight:bold;">
</li>
<li class="clearfix"> #Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long", disabled = "true" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long", disabled = "true" })
</li>
<li>
<div id="slider-range"></div>
</li>
<li>
<input type="submit" value="Search" class="btn-primary" />
</li>
</ul>
</form>
}
After clicking on search it shows like this. Only the data from dropdown is shown and other parameter like Minvalue and max value is not shown in the url. Location is showing
Can anyone help me on how I can successfully get data in the required field in the controller?
It's because your MinValue and MaxValue textboxes have disabled="true" attribute. Disabled inputs won't be submitted
#Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long", disabled = "true" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long", disabled = "true" })
You should remove the disabled attribute
#Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long" })
If you want to make those textboxes non editable, use readonly attribute instead
#Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long", #readonly = "readonly" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long", #readonly = "readonly" })
because you are using disabled attribute true that means it fetches data from database but will not show on View so either make disabled = "false" or remove this attribute.
I updated a Enum Editor I found online to generate kendo radio controls instead of regular but the first radio button is generated with correct attributes and the remaining are wrong and at runtime, the whole set of radio buttons are not clickable
Here is the .cshtml for the editor:
#model Enum
#{
Func<Enum, string> getDescription = en =>
{
Type type = en.GetType();
System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((System.ComponentModel.DataAnnotations.DisplayAttribute)attrs[0]).GetName();
}
}
return en.ToString();
};
var listItems = Enum.GetValues(Model.GetType()).OfType<Enum>().Select(e =>
new SelectListItem()
{
Text = getDescription(e),
Value = e.ToString(),
Selected = e.Equals(Model)
});
string prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
int index = 0;
ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
foreach (var li in listItems)
{
string fieldName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);
<div >
#(Html.Kendo().RadioButton()
.Label(li.Text)
.Name(prefix)
.Value(li.Value)
.Checked(li.Selected)
.HtmlAttributes(new { #id = fieldName })
)
#*
This works properly
#Html.RadioButton(prefix, li.Value, li.Selected, new { #id = fieldName, #class = "k-radio" })
#Html.Label(fieldName, li.Text, new { #class = "k-radio-label" })
*#
</div>
}
ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
}
Here is the first radio on the form:
<div>
<input name="StaffType" class="k-radio k-radio" id="StaffType_0" type="radio" checked="checked" value="DACStaff" data-val-required="The StaffTypeEnum field is required." data-val="true">
<label class="k-radio-label" for="StaffType_0_DACStaff">DAC Staff</label>
</div>
And here is the next one:
<div>
<input name="StaffType" class="k-radio k-radio" id="StaffType_1" type="radio" value="AirportStaff">
<label class="k-radio-label" for="StaffType_1_AirportStaff">Airport Staff</label>
</div>
I see that the class tag k-radio is applied twice and except the first element has the data-* attributes but second radio button and onwards, the generated code is missing attributes.
Can someone point out why the generated code is not functioning?
Usage:
<div class="form-group">
#Html.LabelFor(m => m.StaffType, new { #class = "col-sm-3 control-label" })
<div class="col-sm-6">
#Html.EditorFor(m => m.StaffType, "RadioButtonListEnum")
</div>
</div>
I have a details-view where a varying number of sites are displayed in textboxes. Next to each site the country should be shown in a disabled dropdown. My problem is that the dropdown does not select the right value. Instead it always selects the first item. Some debugging showed that "SelectedCountries[i]" is holding the correct value for each dropdown but somehow this value does not affect the selection at all.
The dropdown's names are "SelectedCountries[i]" and I've read it is bad to use the same name for the dropdown and for the field in the model. However, changing it didn't solve the problem.
<div id="allSitesAndCountries">
#for (int i = 0; i < Model.SelectedSites.Count; i++)
{
#Html.TextBoxFor(m => m.SelectedSites[i], new { disabled = "disabled", })
#Html.DropDownListFor(m => m.SelectedCountries[i], Model.AllCountriesSelectListItems, new{disabled = "disabled"})
}
</div>
What am I doing wrong here?
Thanks in advance.
EDIT: I got it working by creating the SelectList directly in the view and adding the 4th parameter:
<div id="allSitesAndCountries">
#for (int i = 0; i < Model.SelectedSites.Count; i++)
{
<div class="editor-label">
#Html.TextBoxFor(m => m.SelectedSites[i], new { disabled = "disabled"})
#Html.DropDownListFor(m => m.SelectedCountries[i], new SelectList(Model.AllCountries, "Id", "Name", Model.SelectedCountries[i]), new{disabled = "disabled"})
</div>
}
</div>