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
Related
View class
<div class="editor-label">
#Html.LabelFor(model => model.MembershipTypesId, "MembershipTypesId", htmlAttributes: new { #class = "control-label col-md-2" })
</div>
<div class="editor-field">
#Html.DropDownList("MembershipTypesId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MembershipTypesId, "", new { #class = "text-danger" })
</div>
UsersController
public ActionResult Register(Customers customer)
{
if (ModelState.IsValid)
{
using (CDBContext dc = new CDBContext())
{
dc.Customers.Add(customer);
dc.SaveChanges();
ModelState.Clear();
customer = null;
ViewBag.MembershipTypesId = new SelectList(dc.MembershipTypes, "MembershipTypesId", "Name");
ViewBag.Message = "Successfully Registration Done";
}
}
return View(customer);
}
I used the same code for the others view and controller but somehow only this got the error. I tried to remove the null but it still the same.
What your error message suggest is that you are don't have ViewData that you should pass on this DropDownList:
#Html.DropDownList("MembershipTypesId", null, htmlAttributes: new { #class = "form-control" })
It is looking for ViewData with name MembershipTypesId
Your code on controller is correct IF you don't have problem on ModelState, but what if you have an error in your ModelState? Where is your ViewData that you need to pass back on your View?
This should be populated before you return to your View from your Controller:
public ActionResult Register(Customers customer)
{
if (ModelState.IsValid)
{
//Business Logic
}
ViewBag.MembershipTypesId = new SelectList(dc.MembershipTypes, "MembershipTypesId", "Name");
return View();
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I have the following problem with passing data to metod create in controller.
First I display view for method create (GET)
public ActionResult Create(string id)
{
RolesUser RolesUser = new RolesUser(id,repository.GetUserById(id).Roles, repository.GetRoles().ToList());
return View(RolesUser);
}
I use the following ViewModel
public class RolesUser
{
public RolesUser()
{
}
public RolesUser(string id,ICollection<IdentityUserRole> userRoles,List<IdentityRole> Roles)
{
userId = id;
this.Roles = GetNewRolesForUser(userRoles.ToList(), Roles.ToDictionary(x => x.Id, x => x.Name)).ConvertAll(
role =>
{
return new SelectListItem()
{
Text = role.ToString(),
Value = role.ToString(),
Selected = false
};
});
}
public IEnumerable<SelectListItem> Roles { get; set; }
public string userId { get; set; }
private List<string> GetNewRolesForUser(List<IdentityUserRole> UserRoles,Dictionary<string,string> Roles)
{
List<string> AvaiableRoles = new List<string>();
List<string> IdUserRoles = new List<string>();
UserRoles.ForEach(item => IdUserRoles.Add(item.RoleId));
foreach(KeyValuePair<string,string> Role in Roles)
{
if (!IdUserRoles.Contains(Role.Key))
{
AvaiableRoles.Add(Role.Value);
}
}
return AvaiableRoles;
}
}
It displays me essential information on my view in Create.cshtml, when I execute Submit it shows me following error
Object reference not set to an instance of an object.
The metod create (POST) looks like this
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles ="Admin")]
public ActionResult Create([Bind(Include ="userId")] RolesUser user)
{
if (ModelState.IsValid)
{
try
{
repository.AssignToRole(user.userId, "Klient");
repository.SaveChanges();
}
catch
{
ViewBag.exception = true;
return View();
}
}
ViewBag.exception = false;
return RedirectToAction("Index");
}
Code for Create.cshtml
#model Repository.ViewModels.RolesUser
#{
ViewBag.Title = "Create";
}
<h2>Dodaj poziom dostępu</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>#Model.userId</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.userId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.userId, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
#Html.Label("Poziomy dostępu", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.userId, Model.Roles)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
</div>
</div>
</div>
}
It looks like viewmodel is not passing to method, so I have null exception. But I don't understand why, if GET metod render properly view.
The NullReferenceException is likely hit inside the repository.AssignToRole() method because user.userId is null. You should add a hidden input for the userId somewhere inside the form so the userId value is posted to the parameter object on the Create action. If you add it after the #Html.AntiForgeryToken() the start of the form would look like
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.userId)
...
I'm sorry if this question is unclear or I'm not giving enough information, I'm new to CSHTML, and cannot tell if I'm missing something incredibly obvious.
I currently have an EditorFor() in my view that changes the password of a specific userCard field in a database. When this password is being changed, I would like the textbox to be empty, but every time it displays the old value. Deleting the value prior to edit is not an option, for my page has too many options for the user to go to a different page and leave the account passwordless. Any help?
The offending EditorFor is below:
<div class="form-group">
<div class="col-md-10">
<h5>Enter a New Passcode</h5>
</div>
<div class="col-md-10">
#Html.EditorFor(model => model.userCard.password, new { htmlAttributes = new { #class = "form-control"} })
#Html.ValidationMessageFor(model => model.userCard.password, "", new { #class = "text-danger" })
</div>
</div>
The controller methods for this viewpage are below:
public ActionResult EditPasscode(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
UserCardOBJ userCardOBJ = new UserCardOBJ();
userCardOBJ.userCard = db.UserCards.Find(id);
if (userCardOBJ.userCard == null)
{
return HttpNotFound();
}
return View(userCardOBJ);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPasscode([Bind(Include = "ID,password")] UserCard userCard)
{
if (ModelState.IsValid)
{
//db.Entry(userCard).State = EntityState.Modified;
db.UserCards.Attach(userCard);
db.Entry(userCard).Property(model => model.password).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userCard);
}
You could add a value property to the htmlAttribute anonymous type passed in.
#Html.EditorFor(model => model.userCard.password, new { #class = "form-control", #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);
}
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
});
}