i want to pass two models to one view using a ViewModel
My models :
public class Candidat
{
public int Id { set; get; }
public string num_cin { set; get; }
public ICollection<Poste> postes { get; set; }
}
public class Poste
{
public int Id { set; get; }
public string poste_name {set;get}
public List<Candidat> candidats {set;get;}
}
public class PosteCandidatViewModel
{
public Candidat candidat { get; set; }
public Poste poste { get; set; }
}
the controller action :
[HttpPost]
public ActionResult Index( Poste poste,string num_cin)
{
if (ModelState.IsValid)
{
var v = (from c in _db.Candidats
where c.num_cin == num_cin
&& c.postes.Any(p => p.Id == poste.Id)
select c)
.SingleOrDefault();
if (v != null)
{
return RedirectToAction("Inscription", "Candidat");
}
else
{
return RedirectToAction("index", "BureauOrdre");
}
}
return View();
the view :
#model ProcRec.Models.PosteCandidatViewModel
<td>#Html.TextBoxFor(model => model.candidat.num_cin)</td>
<td><p>#Html.DropDownListFor(model => model.poste.Id,new
SelectList(ViewBag.Postes, "Id", "intitule_poste"),"choisir le poste")
</p></td>
my problem is that the linq query is not giving the result i want
(but if i gave to num_cin an poste.id some values it's work )
so the problem is that num_cin not have a valu from dropdownlist ...it's like having an empty value!!!!!!!!!
Change the POST method signature to accept the model, and the access the model properties
[HttpPost]
public ActionResult Index(PosteCandidatViewModel model)
{
Poste poste = model.Poste;
string num_cin = model.Candidat.num_cin;
The reason that parameter string num_cin is null is because #TextBoxFor(model => model.candidat.num_cin) generates <input type="text" name="candidat.num_cin" ... />which is trying to map to property candidat that contains property num_cin. Alternatively upi can use
[HttpPost]
public ActionResult Index( Poste poste, [Bind(Prefix="candidat")]string num_cin)
{
Note, if ModelState is invalid, you need to reassign the the value of ViewBag.Postes that you use in DropDownListFor()
if (ModelState.IsValid)
{
....
}
ViewBag.Postes = // set the value here before returning the view
return View(model);
Related
I have my View page below:
#model ToDoListApp.Models.TodoTable
#{
ViewData["Title"] = "Urgent";
}
#foreach (var item in Model) {
<p>#item.Id</p>
<p>#item.Name</p>
}
Model:
namespace ToDoListApp.Models
{
public partial class TodoTable
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public bool Done { get; set; }
public bool Urgent { get; set; }
}
}
Controller:
[HttpGet]
public IActionResult Urgent(short id)
{
var Task = db.TodoTables.SingleOrDefault(i => i.Id == id);
return View("Urgent", Task);
}
But I am getting an error:
How I can solve the problem?
Solution for IEnumerable
Your ViewModel is not an IEnumerable and the foreach loop requires iterating an IEnumerable value.
Modify the #model as IEnumerable<ToDoListApp.Models.TodoTable> type:
#model IEnumerable<ToDoListApp.Models.TodoTable>
And make sure that your controller action returns the ViewModel as IEnumerable<ToDoListApp.Models.TodoTable> type.
[HttpGet]
public IActionResult Urgent(short id)
{
IEnumerable<TodoTable> tasks = db.TodoTables
.Where(i => i.Id == id)
.ToList();
return View("Urgent", tasks);
}
Solution for a single object
Seems your controller action returns a single object, then you shouldn't use the foreach loop in the View.
#model ToDoListApp.Models.TodoTable
<p>#Model.Id</p>
<p>#Model.Name</p>
I have a model passed from controller to view in my asp.net mvc5 website. Then I show the dropdownlist using the model and I want to pass an id back when submitting the form. Here is my model :
public class SiteDirectionModel
{
public int id { get; set; }
public string name { get; set; }
}
Then in the model, I use a List<SiteDirectionModel> to which I add new instances of each item I need. I fill up both these lists and then pass my model to the view.
#model List<SiteDirectionModel>
#using (Html.BeginForm("GetSiteRF", "Create", FormMethod.Post))
{
#Html.DropDownListFor(x => x.name,new SelectList(Model.name,"Sites"));
<input type="button" value="Selectionner" class="btn btn-primary"/>
}
Then how to retrieve the ids for each name ? And how to pass it as a parameter to my controller? Such that I would have :
public ActionResult GetSiteRF(int id)
{
int newId = id;
//Call method to searchId ...
return View("CreateADUser");
}
I have given how to bind and get value from dropdown. Please use your own BL in this.
Your model should be like this.
public class Something
{
public int Id { get; set; }
public string Name { get; set; }
}
public class SiteDirectionModel
{
public SelectList MyDropDown { get; set; }
public int SelectedValue { get; set; }
}
You BL should be like this.
public List<Something> GetListofSomething()
{
//your logic.
}
Your Get method should be like this.
public ActionResult MyGetMethod()
{
SiteDirectionModel model = new SiteDirectionModel();
model.MyDropDown = new SelectList(GetListofSomething(), "key_field_name", "value_field_name", "default_value");
}
Then finally HTML
#Html.DropDownListFor(x => x.SelectedValue,Model.MyDropDown)
How do I create a DropDownList with values 1-10(int) in view and pass on the selected value to controller?
UserReview model:
public System.Guid Id { get; set; }
public System.Guid UserId { get; set; }
public System.Guid ReviewId { get; set; }
public Nullable<int> Rating { get; set; }
Controller:
public ActionResult Rating(Guid id) //got its ReviewId from previous page
{
//so far empty, no clue what to do
return Content("");
}
1)First Method
In View
<select name="YourDropDownValue">
#for(int i = 1 ; i <= 10 ; i++)
{
<option value="#i">#i</option>
}
</select>
try using this code, In name attribute you have to keep the field name which you want to pass in the controller
In controller this is how you bind dropdown value
[HttpPost]
public ActionResult getDropDown(int YourDropDownValue)
{
}
2)Second Method
Keep this in the controller get
List<int> Num = new List<int>() { 1,2,3,4,5,6,7,8,9,10 };
ViewBag.Number = new SelectList(Num);
Now in view
#Html.DropDownListFor(x => x.YourDropDownValue, ViewBag.Number as SelectList)
if you have no model
#Html.DropDownList("YourDropDownValue", ViewBag.Number as SelectList)
Now in Controller
[HttpPost]
public ActionResult getDropDown(int YourDropDownValue)
{
}
I have seen many examples of passing select list data generated from a ViewModel down to an MVC controller but I have not see an on how to pass the selected value from a normal <select> HTML5 tag. For example, in my View I have :
<select id="Type">
<option value="Game">Game</option>
<option value="Collection">Collection</option>
<option value="Cinema">Cinema</option>
<option value="Book">Book</option>
</select>
How do I pass the selected value from that select list down to my controller so I can then add it into my EF model?
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddSection(Section NewSection, HttpPostedFile LogoFile)
{
if (ModelState.IsValid)
{
try
{
if (LogoFile != null && LogoFile.ContentLength > 0)
{
if (LogoFile.ContentType == "image/png")
{
string FileName = NewSection.RouteName + "Logo";
NewSection.LogoFileID = FileUploadHelper.UploadSiteImage("Logos", FileName, LogoFile);
}
else
{
ModelState.AddModelError("File Type", "Logo Files must be PNG files.");
return View(NewSection);
}
}
using (db)
{
db.Sections.Add(NewSection);
db.SaveChanges();
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
ModelState.AddModelError("Processing Error", "There was a problem processing the new section, please try again later.");
return View(NewSection);
}
}
return View(NewSection);
}
Model:
public class Section
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int16 ID { get; set; }
public Int64? LogoFileID { get; set; }
[Required, MaxLength(250), Column(TypeName = "varchar")]
public string RouteName { get; set; }
[Required, MaxLength(15), Column(TypeName = "varchar")]
public string Type { get; set; }
[Required]
public string Title { get; set; }
public string Synopsis { get; set; }
[ForeignKey("LogoFileID")]
public virtual File Logo { get; set; }
}
You should set the select's name attribute to the same value as the name of the parameter expected by the controller.
[HttpPost]
public ActionResult Edit(string type)
{
//do work
}
html:
<select id="Type" name="Type">
options...
</select>
If you are posting a complex model like
public class ViewModel
{
public string Type { get; set; }
}
to the controller:
[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
//do work
}
select's name attribute should be equal to the model's property name ("Type" as well).
If you don't want to follow this convention for some reason, you can also access the posted values from controller using the Request.Form property.
You also need to change action's signature to
public ActionResult AddSection(Section NewSection, HttpPostedFileBase LogoFile)
to bind the file.
So I've looked around StackOverflow a lot and found a nice solution to my problem.
MVC3 DropDownListFor - a simple example?, this ought to do it for me. BUT, it returned a null value... Somehow I have no idea how to go around this so assistance will be appreciated.
Model AccountModel.cs
...
public string Address { get; set; }
public string City { get; set; }
public class StateList
{
public int StateID { get; set; }
public string Value { get; set; }
}
public IEnumerable<StateList> StateListOptions = new List<StateList>
{
//new StateList { StateID = -1, Value = "Select State" },
new StateList { StateID = 0, Value = "NY" },
new StateList { StateID = 1, Value = "PO" }
};
public string State { get; set; }
public string Zip { get; set; }
...
Register.cshtml
#Html.DropDownListFor(m => m.State, new SelectList(Model.StateListOptions, "StateID", "Value", Model.StateListOptions.First().StateID))
I thought maybe my StateID = -1 made it output a null for some reason... but it didn't, you can see it commented out here. What did I do wrong?!
Get Action
public ActionResult Register()
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View();
}
Create an object of your Model/ ViewModel and send that to view.
public ActionResult Register()
{
AccountModel vm=new AccountModel();
//Not sure Why you use ViewData here.Better make it as a property
// of your AccountModel class and pass it.
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
return View(vm);
}
Now your View should be strongly typed to this Model
So in your Register.cshtml view,
#model AccountModel
#using(Html.BeginForm())
{
//Other form elements also
#Html.DropDownListFor(m => m.State, new SelectList(Model.StateListOptions,
"StateID", "Value")"Select")
<input type="submit" />
}
To Get the Selected State in POST, You can check the State Property value.
[HttpPost]
public ActionResult Register(AccountModel model)
{
if(ModelState.IsValid)
{
// Check for Model.State property value here for selected state
// Save and Redirect (PRG Pattern)
}
return View(model);
}