Html.HiddenFor with preset value - asp.net-mvc

This part was sloved thanks to Ethan Brown
I want to set the value of my Html.HiddenFor helper with preset value
This is my code :
<%: Html.HiddenFor(model => model.idv, new { #value = ViewBag.id })%>
<%: Html.HiddenFor(model => model.etat, new { #value = "false" })%>
But when execute my code i get the error that model.idv and modele.etat are null.
This is seconde part no sloved till now :
This is my action :
public ActionResult Reserver(string id)
{
var model = new Models.rservation
{
idv = id,
etat = false
};
return View(model);
}
[HttpPost]
public ActionResult Reserver(Models.rservation model)
{
if (ModelState.IsValid)
{
entity.AddTorservation(model);
entity.SaveChanges();
return View();
}
else
{
return View(model);
}
}
And this is my view page :
<% using (Html.BeginForm("Reserver", "Home", FormMethod.Post, new { #class = "search_form" })) { %>
//some code textbox to fill
<input type="submit" value="Create" />
<% } %>
So when i click on submit button the model.idv is set again on null value

The correct way to set a preset value is to pass it in via the model (MVC appears to ignore the "value" parameter if you set it). To accomplish what you're looking for, in your action:
public ActionResult MyAction() {
var model = new MyModel {
idv = myPresetId,
etat = false
};
return View( model );
}
Then you don't have to do anything in your view except have:
<%: Html.HiddenFor( model => model.idv ) %>
<%: Html.HiddenFor( model => model.etat ) %>

Related

#Html.CheckBoxFor is enabled or not and get the true or false in controller based on selection

In Cshtml file I have created a checkbox and using that true or false value of check box, need to write the logic in controller
In cshtml file
#Html.Checkboxfor(m=>m.isChecked,new {id="isChecked"}) #Html.Label("Ischecked",new {id="lblIsChecked", #class = "control-label"
In Model.cs
public bool isChecked {get;set;}
In controller
Model model=new Model();
If(model.isChecked == true)
{
//Logic to write
}
While checking isCheked variable in controller, I'm getting only false. Clarify this.
Below is a work demo, you can refer to it:
In Controller:
public IActionResult Index()
{
Model model = new Model();
return View(model);
}
[HttpPost]
public IActionResult Index(Model model)
{
if (model.isChecked == true)
{
//Logic to write
}
return View();
}
view:
#model Model
#using (Html.BeginForm())
{
#Html.CheckBoxFor(m => m.isChecked)
#Html.Label("ischecked","isChecked",new {id="lblIsChecked", #class = "control-label"})
<br/>
<input type="submit" value="submit" />
}
result:

Check validations dynamically in Controller [ASP.Net MVC]

I'm developing an MVC application for Travels portal. Here, I have a form to submit a new Travel request and my controller looks like this
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(CreateOrEditCabBookingDto model)
{
if (ModelState.IsValid)
{
CabBookingAppService.Instance.CreateOrUpdate(model);
}
return PartialView("_CreateOrUpdateCabBooking", model);
}
I have not included any validation annotations to my Model because I want them to execute dynamically based on some conditions. Is it possible to have validations dynamically in controller and add them to Model State?
Example: Based on StatusId property value, set StartDate as Required.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(CreateOrEditCabBookingDto model)
{
if (ModelState.IsValid)
{
If(model.StatusId == 10)
{
// Check validation here
// Property "StartDate" is Required
}
CabBookingAppService.Instance.CreateOrUpdate(model);
}
return PartialView("_CreateOrUpdateCabBooking", model);
}
Based on the inputs, I changed like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(CreateOrEditCabBookingDto model)
{
if (string.IsNullOrEmpty(model.FromDateTime))
{
ModelState.AddModelError("FromDateTime","Date is Required");
}
if (ModelState.IsValid)
{
CabBookingAppService.Instance.CreateOrUpdate(model);
}
return PartialView("_CreateOrUpdateCabBooking", model);
}
And My View Looks like this:
#using (Ajax.BeginForm("CreateOrEdit", "Travel", null, new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnBegin = "OnBegin",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "PopupId"
}, new { id = "frm" }))
{
............................
<div class="form-group col-md-3">
#Html.LabelFor(model => model.FromDateTime)
#Html.TextBoxFor(model => model.FromDateTime, new { #class = "form-control datetimepicker", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.FromDateTime)
</div>
............................
}

#Html.DisplayFor() value not change after the postback

#Html.DisplayFor() value not change after send data. I read a article about this issue and say it like this; only send data what such as EditorFor, TextBoxFor, TextAreaFor and change state. Is it true? How can I change this value after the postback?
View
#model HRProj.Model.Person
#using(Html.BeginForm("Skills", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.HiddenFor(m => m.SkillDoc.Filename)
<span class="file-upload">
<span>Choose a file</span>
<input type="file" name="file" />
</span>
File name : #Html.DisplayFor(m => m.SkillDoc.Filename)
<button>Upload</button>
}
Controller
public ActionResult Skills(int? id)
{
Others oparations...
var model = new Person { SkillDoc = db.GetSkillDoc().FirstOrDefault(m => m.PersonId == id) };
return View(model);
}
[HttpPost]
public ActionResult Skills(Person model, HttpPostedFileBase file)
{
Others oparations...
if (ModelState.IsValid)
{
SkillDoc doc = new SkillDoc();
doc.Id = model.SkillDoc.Id;
doc.PersonId = model.SkillDoc.PersonId;
doc.CvDoc = (file != null) ? file.FileName : model.SkillDoc.CvDoc;
db.SkillDocCRUD(doc, "I");
TempData["eState"] = "The record adding successfully";
if (file != null)
{
file.SaveAs(Server.MapPath("~/Files/" + file.FileName));
}
}
return View(model);
}
Please add the following line inside the if block:
model.SkillDoc=doc;
Or rather redirect to Skills action:
return RedirectToAction("Skills", new{id= model.PersonId});

DropdownList With Data Entity Framework

This is my DropdownList :
<div class="editor-label">
<p>
<%: Html.LabelFor(model => model.Gov) %>
</p>
</div>
<div class="editor-field">
<p>
<%=Html.DropDownListFor(model => model.Gov, ViewBag.gov as SelectList)%>
<%: Html.ValidationMessageFor(model => model.Gov) %>
</p>
and this is my view controller :
public ActionResult TestR()
{
ViewBag.gov = new SelectList(entity.gouvernerat, "Idgov", "Nomg");
return View();
}
With HttpPost :
[HttpPost]
public ActionResult TestR(LogModel.preRegister Model)
{
if (ModelState.IsValid)
{
if (LogModel.preRegister.Verifuser(Model.IDag))
{
ModelState.AddModelError("", "Agence existe deja");
return View(Model);
}
else
{
int ins = LogModel.preRegister.Register(Model);
if (ins > 0)
{
return View("Index");
}
else return View();
}
}
else
{
return View();
}
}
Now Dropdown list show me the list of Gov in my DB(that's what i want), but when i clic on create i got this error in my DropdownLisrt There is no ViewData item of type 'IEnumerable <SelectListItem>' with key 'Gov'.
This is pretty easy with LINQ to SQL. Let's say you have a table Govs that contains your "Tunis", "Ariana", etc. strings. You can then create your select list like this:
govs.Select( x => new SelectListItem { Text = x.Name, Value = x.Name } );
Of course you can even be more flexible and assign the value to something else, like an ID.
Update: more details to answer questions posed in comments:
Add the select list items in the view model:
public IEnumerable<SelectListItem> GovItems { get; set; }
Then, in the controller, before returning your view:
// database code to get "Govs" table goes here....
var vm = new MyViewModel {
GovItems = govs.Select( x => new SelectListItem { Text = x.Name, Value = x.Name } );
}
Then in your view:
#Html.DropDownListFor( x => x.Gov, Model.Govs )
I hope this helps. If you're still confused, I recommend reading some tutorials about ASP.NET MVC. I recommend Microsoft's official one:
http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part1-cs

problems with html helper method

I can't figure out how to send a parameter from a dropdownlist to my model. Could someone please show me an example of how to do this?
As always you start by defining a model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public SelectList Items
{
get
{
return new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}, "Value", "Text");
}
}
}
Controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// You will get the selected value inside model.SelectedValue here
// => do something with it
....
}
}
Strongly typed view:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedValue, Model.Items) %>
<input type="submit" value="OK" />
<% } %>
public ActionResult Edit(int id)
{
Affiliate affiliate = affiliateRepository.GetAffiliate(id);
List<SelectListItem> StateList = new List<SelectListItem>();
SelectListItem item;
Dictionary<string, string> dictState = S127Global.Misc.getStates();
foreach (KeyValuePair<string, string> k in dictState)
{
item = new SelectListItem();
item.Text = k.Value;
item.Value = k.Key;
StateList.Add(item);
}
item = new SelectListItem();
item.Text = " - Select State - ";
item.Value = "";
StateList.Insert(0, item);
//create new select list with affiliate.state as the selected value in ViewData
ViewData["State"] = new SelectList(StateList.AsEnumerable(), "Value", "Text",affiliate.State);
return View(affiliate);
}
code for view
<div class="editor-label">
<%: Html.LabelFor(model => model.State) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("State")%>
<%: Html.ValidationMessageFor(model => model.State) %>
</div>

Resources