Using a html select box with razor - asp.net-mvc

I have a html selector, and I want to use the selected value for my "model => model.type" in my form. Is there a way to set the value in my #Html.EditorFor(model => model.type) to the value of the selector?
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Bet</legend>
<div class="editor-label">
#Html.LabelFor(model => model.type)
</div>
<div class="editor-field">
<select id ="type">
<option value="Football">Football</option>
<option value="Rugby">Rugby</option>
<option value="Horse Racing">Horse Racing</option>
</select>
#Html.EditorFor(model => model.type)
#Html.ValidationMessageFor(model => model.type)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>

You can try with this options:
Model:
public string Type { get; set; }
public IEnumerable<SelectListItem> TypeList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "Football", Value = "Football"},
new SelectListItem { Text = "Rugby", Value = "Rugby"},
new SelectListItem { Text = "Horse Racing", Value = "Horse Racing"}
};
}
}
HTML (Razor):
#Html.DropDownListFor(model => model.Type, Model.TypeList)
OR
HTML (Razor):
#Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, Model.Type))

#andresdescalzo's solution (last one) works with a minor change:
#Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, "Rugby"), htmlAttributes: new { #class = "form-control" })
First: Add a selected item for dropdown list (e.g. "Rugby")
Second: remove last Model.Type and add htmlAttributes
PS: SelectedList open parentheses closed after selected item of list (here is "Rugby")

The solution provided by #andresdescalzo works only when we pass the model from Controller to the view.
public class SomeController : Controller
{
public ActionResult SomeAction()
{
return View(new SomeModelWithIEnumerationsSelectListItem())
}
}

An addition to the existing answers: If you get the exception "object reference not set to an instance of an object" when implementing #andresdescalzo's solution, you either need to:
Return the model that you are working with as #diwas mentioned
Instantiate a model on the razor page so you can call the method. This is helpful if you are using a ViewModel instead of a simple EF model.
The second can be done like this:
#{ var tempModel = new YourNameSpace.Models.YourModel(); }
#Html.DropDownListFor(model => model.Type, tempModel.TypeList, Model.Type))

This is the Razor View
<div class="editor-field col-md-3">
#Html.DropDownListFor(model => model.Servers,
Model.AvailableServers,new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SqlServerName)
</div>
Dynamic DropDown from controller
List<SelectListItem> ServersAvailable = new List<SelectListItem>();
bool IdSelected = false;
ServersAvailable.Add(new SelectListItem { Text = "......Select your server name......", Value = "" });
for (int i = 0; i < dt.Rows.Count; i++)
{
ServersAvailable.Add(new SelectListItem
{
Text = dt.Rows[i].ItemArray[0].ToString(),
Value = dt.Rows[i].ItemArray[0].ToString(),
Selected = IdSelected
});
}

Related

Selected Option is not Working in MVC Razor View

I'm unable to get selected value in dropdown using simple below code -
<select class="form-control" id="team-name" name="gameTypes">
#{long selectedOption = #ViewBag.HomeTeamId;}
#foreach (var item in Model.teams)
{
<option value="#item.TeamId" data-logo="#item.LogoURL" selected="#(selectedOption == #item.TeamId ? "selected" : "")">#item.FullName</option>
}
</select>
I would do it like this:
Write your method to get the needed Teams in a List<SelectListItem> and then in your controller put the values in a ViewBag (ViewBag.Teams = GetTeams();)
For exmaple:
[NonAction]
private List<SelectListItem> GetTeams()
{
IEnumerable<Team> teams = new List<Team>();
//fill the teams here from the DB
return teams.Select(team => new SelectListItem
{
Text = team.TeamName, //here you can select the property that you want to show as text in the dropdown
Value = team.ID.ToString()
}).ToList();
}
And in your view, retrieve
#{
List<SelectListItem> teams = ViewBag.Teams as List<SelectListItem>;
}
And here define your dropdown and pass teams as the datasource:
<div class="col-md-6 form-group">
#Html.LabelFor(model => model.TeamId, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.TeamId, teams, "Select a team", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TeamId, "", new { #class = "text-danger" })
</div>

BeginForm not showing initial Dropdown List Value

I am using BeginForm and the initial value of one of the Dropdown's is not being set properly. The value is held in a SelectLitemItem and is correctly shown in the preceding Table (in the Index view). The available values provided for list are also correct. It always defaults to "Create" which has a value of "1" even when it should be "Update" which has a value of "2".
The Model.RuleType.Value is shown correctly if I just display it on the form.
I cannot see what I'm doing wrong. I can see no duplicate ID/ Name and have tried including a Hidden field.
There is another dropdown that happens to use a common value for both Value and Text and that works.
Any ideas?
Thanks.
#model AMS.Web.Areas.Admin.Models.RuleActionModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true) #Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.RuleType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Partial("Partials/_RuleTypeDropdown") #Html.ValidationMessageFor(model => model.RuleType)
</div>
</div>
RuleTypeDropdown
#using Kendo.Mvc.UI;
#(Html.Kendo().DropDownList()
.Name("RuleType")
.DataTextField("Text")
.DataValueField("Value")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("RuleTypeList", "List", new { Area = "Admin" });
});
})
)
Model
public class RuleActionModel
{
public RuleActionModel() { }
public RuleActionModel(RuleAction ruleAction)
{
...
RuleType = new SelectListItem()
{
Value = ruleAction.RuleType.ToString(),
Text = ((RuleType)(ruleAction.RuleType)).EnumToString()
};
}
[Display(Name = "Type")]
public SelectListItem RuleType { get; set; }
Controller
public ActionResult Edit(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
RuleAction ruleAction = UnitOfWork.RuleActionRepository.FirstOrDefault(x => x.ID == id);
if (ruleAction == null)
{
return HttpNotFound();
}
var model = new RuleActionModel(ruleAction);
return View(model);
}

MVC send dropdown value to databse and post it in table

Hi i am new in mvc and I'm trying to send my dropdown value to database and post it to table, any suggest best way how it will work ? .. thanks in advance
ContactController.cs
public ActionResult Create()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "English", Value = "0", Selected = true });
items.Add(new SelectListItem { Text = "German", Value = "1" });
items.Add(new SelectListItem { Text = "Spanish", Value = "2"});
items.Add(new SelectListItem { Text = "Italian", Value = "3" });
ViewBag.LanguageList = items;
return View();
}
Create.cshtml
<div class="editor-label">
#Html.LabelFor(model => model.language)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.language, new SelectList(ViewBag.LanguageList))
#Html.ValidationMessageFor(model => model.language)
</div>
Index.cshtml
<td>
#Html.DisplayFor(modelItem => item.language)
</td>
Ok, put your Dropdown selection in a form with a submit button:
using (Html.BeginForm("Create", "ContactController", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="editor-label">
#Html.LabelFor(model => model.language)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.language, new SelectList(ViewBag.LanguageList))
#Html.ValidationMessageFor(model => model.language)
</div>
<input type="submit" value="Enable" class="btn btn-link" />
}
Controller:
//This action can only be accessed with the Http.Post verb
[HttpPost]
//Validate the antiforgerytoken we set with `#Html.AntiForgeryToken()` in the view (Prevents CSRF attacks)
[ValidateAntiForgeryToken]
public ActionResult Create(YourModel model)
{
//Your model will now contain the value of the selected dropdown if you have wired up your model correctly.
//Connect to db, persist model.language
return View();
}

how to insert fixed value into table in MVC

I want to insert a fixed date into table. How can I do this ?
<div class="editor-label">
Description :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Description, new { #class = "textboxes" })
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
Date :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Date, new { #class = "textboxes" }) /// I wanna be here a fixed date .
#Html.ValidationMessageFor(model => model.Date)
</div>
My controller code is:
public ActionResult Index(tblOrder tblorder)
{
if (ModelState.IsValid)
{
db.tblOrders.AddObject(tblorder);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.fxBudjet = new SelectList(db.tblBudjets, "ID", "Budjet", tblorder.fxBudjet);
ViewBag.fxServiceType = new SelectList(db.tblServiceTypes, "ID", "Service", tblorder.fxServiceType);
ViewBag.fxStartTime = new SelectList(db.tblStartDates, "ID", "StartDate", tblorder.fxStartTime);
return View(tblorder);
}
Do I need to change my controller code?
#Html.DisplayTextFor(model => model.Date, new { #class = "textboxes" })
if the date is needed in a post you can do
#Html.DisplayTextFor(model => model.Date, new { #class = "textboxes" })
#Html.HiddenFor(model => model.Date)
or in the post method you can use TryUpdateModel and exclude the date field
Edit from your update i would set the value for the model in the controller e.g. say you had a class year that you wanted to prepopulate the year value
public ActionResult Create()
{
return View(new Year() { Value = DateTime.Now.Year });
}
again if you want it for the post you can use a hiddenfor or else regenerate it in the post
if this field is only required in the post method a better option might be to create a viewmodel without that field and then have some mapping logic in the post method
Edit 2: As with MVC music store you should really have 2 methods a get and a post. I will assume it is for a create.
[HttpGet]
public ActionResult Create()
{
ViewBag.fxBudjet = new SelectList(db.tblBudjets, "ID", "Budjet");
ViewBag.fxServiceType = new SelectList(db.tblServiceTypes, "ID", "Service");
ViewBag.fxStartTime = new SelectList(db.tblStartDates, "ID", "StartDate");
return View(new tblOrder() { Date = DateTime.Now });
}
[HttpPost]
public ActionResult Create(tblOrder tblorder)
{
if (ModelState.IsValid)
{
db.tblOrders.AddObject(tblorder);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.fxBudjet = new SelectList(db.tblBudjets, "ID", "Budjet", tblorder.fxBudjet);
ViewBag.fxServiceType = new SelectList(db.tblServiceTypes, "ID", "Service", tblorder.fxServiceType);
ViewBag.fxStartTime = new SelectList(db.tblStartDates, "ID", "StartDate", tblorder.fxStartTime);
return View(tblorder);
}
then in your view something like
#model tblOrder
#Html.BeginForm()
{
#Html.DisplayTextFor(model => model.Date, new { #class = "textboxes" })
#Html.HiddenFor(model => model.Date)
...other form stuff
<input type="submit" value="Delete" />
}
Hopefully this should give you some idea of how to fix your code

No value for the dropdownlist when my form is submitted

I try to use a dropdownlist in my view for showing a list of authors (users). I'm able to populate this dropdown and see the content in my view. When submitting my form, I debug my action in my controller and when inspecting my model, the value of the field associated with my dropdown is null.
Here is my action controller (before showing my view):
public ActionResult Create()
{
IEnumerable<User> authors = m_AccountBusiness.GetAllUsers();
PageCreateViewModel viewModel = new PageCreateViewModel
{
PageToCreate = new PageFullViewModel(),
Authors = authors.Select(x => new SelectListItem { Text = x.UserName, Value = x.UserID.ToString() })
};
return View(viewModel);
}
Here is (a portion of) my view:
#model MyBlog.ViewModels.PageCreateViewModel
<h3>Create</h3>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.PageToCreate.PageID)
<div class="editor-label">
#Html.LabelFor(model => model.PageToCreate.Title)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PageToCreate.Title, new { #class = "titleValue" })
#Html.ValidationMessageFor(model => model.PageToCreate.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PageToCreate.Author)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.PageToCreate.Author, Model.Authors, "Please select...")
</div>
Here is my PageCreateViewModel:
public class PageCreateViewModel
{
public PageFullViewModel PageToCreate { get; set; }
public IEnumerable<SelectListItem> Authors { get; set; }
}
Any idea?
Thanks.
Thank you guys. I finally found my error: it is not Author the right property to bind to, it must be AuthorID !!
<div class="editor-field">
#Html.DropDownListFor(model => model.PageToCreate.AuthorID, Model.Authors, "Please select...")
</div>
Thanks anyway.
You have to add an extra string property to your PageCreateViewModel. In this property we will store the selected value. Lets say it's name is "Author". Edit: I noticed you have a property for it in your model but give it a try like this.
The dropdownlist filling needs to look like this on your view.
#Html.DropDownList("Author", Model.Authors)

Resources