#model IEnumerable<Evidencija.Models.Vozilo>
#{
ViewBag.Title = "PokreniIzvjestaj";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>PokreniIzvjestaj</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Vozilo</legend>
<p>
#Html.DropDownList("Vozila", Model.Select(p => new SelectListItem { Text = p.VoziloID.ToString(), Value = p.VoziloID.ToString() }), "Izaberi vozilo")
</p>
<input type="submit" value="Dodaj stavku" />
</fieldset>
}
I want to send id of table vozilo to controler with dropdownlist.
Controler accepts vozilo as a parameter but it is ollways zero.
How can I solve this without using viewmodel.
[HttpPost]
public ActionResult PokreniIzvjestaj(Vozilo v)
{
ReportClass rpt = new ReportClass();
rpt.FileName = Server.MapPath("~/Reports/Vozilo.rpt");
rpt.Load();
//ReportMethods.SetDBLogonForReport(rpt);
//ReportMethods.SetDBLogonForSubreports(rpt);
// rpt.VerifyDatabase();
rpt.SetParameterValue("#VoziloId",v.VoziloID);
Stream stream = null;
stream = rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
return File(stream, "application/pdf", "Vozilo.pdf");
//PortableDocFormat--pdf format
//application/pdf -- vezan za pdf format, ako je drugi tip mjenja se u zavisnosti od izabranog
//naziv.pdf -- naziv dokumenta i izabrana ekstenzija
}
[HttpGet]
public ActionResult PokreniIzvjestaj()
{
var vozila = db.Voziloes.ToList();
return View(vozila);
}
There are two method from controler.
You currently binding your drop down to a property named Vozilo. A <select> post back single value (in your case the VoziloID or the selected option. Your POST method then tries to bind a complex object Vozilo to an int (assuming VoziloID is typeofint) which of course fails and the model isnull`. You could solve this changing the method to
[HttpPost]
public ActionResult PokreniIzvjestaj(int Vozilo)
The parameter Vozilo will now contain the value of the selected VoziloID.
However it not clear why you want to "solve this without using viewmodel" when using a view model is the correct approach
View model
public class VoziloVM
{
[Display(Name = "Vozilo")]
[Required(ErrorMessage = "Please select a Vozilo")]
public int? SelectedVozilo { get; set; }
public SelectList VoziloList { get; set; }
}
Controller
public ActionResult PokreniIzvjestaj()
{
var viziloList = db.Voziloes.Select(v => v.VoziloID);
VoziloVM model = new VoziloVM();
model.VoziloList = new SelectList(viziloList)
model.SelectedVozilo = // set a value here if you want a specific option selected
return View(model);
}
[HttpPost]
public ActionResult PokreniIzvjestaj(VoziloVM model)
{
// model.SelectedVozilo contains the value of the selected option
....
}
View
#model YourAssembly.VoziloVM>
....
#Html.LabelFor(m => m.SelectedVozilo)
#Html.DropDownListFor(m => m.SelectedVozilo, Model.VoziloList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedVozilo)
....
Related
How to get the textbox value from view to controller in mvc4?If I using httppost method in controller the page cannot found error was came.
View
#model MVC_2.Models.FormModel
#{
ViewBag.Title = "DisplayForm";
}
#using (Html.BeginForm("DisplayForm", "FormController", FormMethod.Post))
{
<form>
<div>
#Html.LabelFor(model => model.Empname)
#Html.TextBoxFor(model => model.Empname)
#* #Html.Hidden("Emplname", Model.Empname)*#
#Html.LabelFor(model => model.EmpId)
#Html.TextBoxFor(model => model.EmpId)
#* #Html.Hidden("Emplid", Model.EmpId)*#
#Html.LabelFor(model => model.EmpDepartment)
#Html.TextBoxFor(model => model.EmpDepartment)
#* #Html.Hidden("Empldepart", Model.EmpDepartment)*#
<input type="button" id="submitId" value="submit" />
</div>
</form>
}
model
public class FormModel
{
public string _EmpName;
public string _EmpId;
public string _EmpDepartment;
public string Empname
{
get {return _EmpName; }
set { _EmpName = value; }
}
public string EmpId
{
get { return _EmpId;}
set {_EmpId =value;}
}
public string EmpDepartment
{
get { return _EmpDepartment; }
set { _EmpDepartment = value; }
}
}
controller
public ActionResult DisplayForm()
{
FormModel frmmdl = new FormModel();
frmmdl.Empname=**How to get the textbox value here from view on submitbutton click???**
}
First you need to change your button type to "submit". so your form values will be submitted to your Action method.
from:
<input type="button" id="submitId" value="submit" />
to:
<input type="submit" id="submitId" value="submit" />
Second you need to add your model as parameter in your Action method.
[HttpPost]
public ActionResult DisplayForm(FormModel model)
{
var strname=model.Empname;
return View();
}
Third, If your Controller name is "FormController". you need to change the parameter of your Html.Beginform in your view to this:
#using (Html.BeginForm("DisplayForm", "Form", FormMethod.Post))
{
//your fields
}
P.S.
If your view is the same name as your Action method which is "DisplayForm" you don't need to add any parameter in the Html.BeginForm. just to make it simple. like so:
#using (Html.BeginForm())
{
//your fields
}
Have an ActionResult for the form post:
[HttpPost]
public ActionResult DisplayForm(FormModel formModel)
{
//do stuff with the formModel
frmmdl.Empname = formModel.Empname;
}
Look into Model Binding. Default model binding will take the data embedded in your posted form values and create an object from them.
Let's implement simple ASP.NET MVC subscription form with email textbox.
Model
The data from the form is mapped to this model
public class SubscribeModel
{
[Required]
public string Email { get; set; }
}
View
View name should match controller method name.
#model App.Models.SubscribeModel
#using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
<button type="submit">Subscribe</button>
}
Controller
Controller is responsible for request processing and returning proper response view.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Subscribe(SubscribeModel model)
{
if (ModelState.IsValid)
{
//TODO: SubscribeUser(model.Email);
}
return View("Index", model);
}
}
Here is my project structure. Please notice, "Home" views folder matches HomeController name.
You model will be posted as a object on the action and you can get it in action on post like this:
[HttpPost]
public ActionResult DisplayForm(FormModel model)
{
// do whatever needed
string emp = model.EmpName;
}
it you are posting data always put HttpPost attribute on the action.
Your view also has mistakes, make it like this:
#using (Html.BeginForm("DisplayForm", "Form", FormMethod.Post))
{
<div>
#Html.LabelFor(model => model.Empname)
#Html.TextBoxFor(model => model.Empname)
#* #Html.Hidden("Emplname", Model.Empname)*#
#Html.LabelFor(model => model.EmpId)
#Html.TextBoxFor(model => model.EmpId)
#* #Html.Hidden("Emplid", Model.EmpId)*#
#Html.LabelFor(model => model.EmpDepartment)
#Html.TextBoxFor(model => model.EmpDepartment)
#* #Html.Hidden("Empldepart", Model.EmpDepartment)*#
<input type="button" id="submitId" value="submit" />
</div>
}
There are two ways you can do this.
The first uses TryUpdateModel:
public ActionResult DisplayForm()
{
FormModel frmmdl = new FormModel();
TryUpdateModel (frmmdl);
// Your model should now be populated
}
The other, simpler, version is simply to have the model as a parameter on the [HttpPost] version of the action:
[HttpPost]
public ActionResult DisplayForm(FormModel frmmdl)
{
// Your model should now be populated
}
Change your controller like below.
[HttpPost]
public ActionResult DisplayForm(FormModel model)
{
var Empname = model.Empname;
}
You need to have both Get and Post Methods:
[HttpGet]
public ActionResult DisplayForm()
{
FormModel model=new FormModel();
return View(model);
}
[HttpPost]
public ActionResult DisplayForm(FormModel model)
{
var employeeName=model.Empname;
return View();
}
[HttpPost]
public ActionResult DisplayForm(FormModel model)
{
var value1 = model.EmpName;
}
Model values from hidden field? I recommend the strongly typed approach shown below:
public ActionResult DisplayForm(string Emplname, string Emplid, string Empldepart)
[HttpPost]
public ActionResult DisplayForm(FormModel model)
{
FormModel frmmdl = new FormModel();
frmmdl.Empname=**How to get the textbox value here from view on submitbutton //click???**
}
model.Empname will have the value
My dropdown is pulling and displaying the correct list, however once selected, I click save and the selected option is disregarded and once again the value is empty.
//get
public ActionResult Edit(int id)
{
Prospect prospect = db.Prospects.Find(id);
if (prospect == null)
{
return HttpNotFound();
}
ViewBag.ProductID = new SelectList(db.Products, "ProductID", "Name", prospect.Product);
return View(prospect);
}
//post
[HttpPost]
public ActionResult Edit(Prospect prospect)
{
if (ModelState.IsValid)
{
db.Entry(prospect).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProductID = new SelectList(db.Products, "ProductID", "Name", prospect.Product);
return View(prospect);
}
//view
<div class="editor-label">
#Html.LabelFor(model => model.Product)
</div>
<div class="editor-field">
#Html.DropDownList("ProductId", String.Empty)
#Html.ValidationMessageFor(model => model.Product)
</div>
Any help will be greatly appreciated
only for helpers (except display) are tied to the model. change your drop down list to
#Html.DropDownListFor(x => x.ProductID, (SelectList)ViewBag.ProductID)
where ProductID is whatever value in your model you want the selected item tied to. You also set the drop down this way by setting that value before passing it to the view
Update:
I agree with Muffin Mans answer. Using ViewBag to send drop down lists to the view can be unreliable. A different way to put the answer the muffin man provided
Add an list to your model
public List<SelectListItem> Products { get; set; }
then on your controller populate that list from the database. Muffin Man provided one way to do it. We access our data differently so I populate my list with a foreach
var products = //populate the list from your database
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in products){
ls.Add(new SelectListItem() { Text = temp.ProductName, Value = temp.ProductID });
}
Model.Products = ls; // set the list in your model to the select list you just built
then on your view instead of casting a view bag list to a select list you can just reference the list from the model
#Html.DropDownListFor(x => x.ProductID, Model.Products)
You shouldn't be tying your view directly to your database table type. Use a view model. Additionally this type of data belongs in your view model, not the viewbag. The view bag is great for sharing things like page title between your view and the layout page.
public class ProspectViewModel
{
public IEnumerable<SelectListItem> ProspectList { get; set; }
[DisplayName("Product")] //This is for our label
public int SelectedProspectId { get; set; }
}
Get
public ActionResult Edit(int id)
{
var prospect = db.Prospects.Find(id);
if (prospect == null)
{
return HttpNotFound();
}
var model = new ProspectViewModel
{
ProductList = db.Products.Select(x=> new SelectListItem { ... })
};
return View(model);
}
Post
[HttpPost]
public ActionResult Edit(ProspectViewModel model)
{
if (ModelState.IsValid)
{
var prospect = new Prospect { /* populate with values from model */ };
db.Prospects.Attach(prospect);
db.Entry(prospect).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
//Need to repopulate drop down list
//And we don't need to set SelectedProductId because it's already been posted back
model.ProductList = db.Products.Select(x=> new SelectListItem { ... });
return View(model);
}
View
<div class="editor-label">
#Html.LabelFor(model => model.SelectedProductId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x=> x.SelectedProductId, Model.ProductList)
#Html.ValidationMessageFor(x=> x.SelectedProductId)
</div>
This is outside the scope of this answer, but you shouldn't be doing data access within your controller. Microsoft's examples show this because they are meant to be "Hello world" examples, not necessarily to be taken literally.
Hi I have got a drop downlist that I am binding that one in controller I have got one button in view with that I am doing some validations that's working fine,
when I submit the button for validation check i am not able to get the view with error message. Instead of this I am getting error like this " The view 'PostValues' or its master was not found or no view engine supports the searched locations".
would any one help on why I am not able to get the view
here the view is strongly Typed view
and this is my code in controller.
public class CrossFieldsTxtboxesController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
var model = NewMethod();
return View(model);
}
private static CrossFieldValidation NewMethod()
{
var model = new CrossFieldValidation
{
SelectedValue = "Amount",
Items = new[]
{
new SelectListItem { Value = "Amount", Text = "Amount" },
new SelectListItem { Value = "Pound", Text = "Pound" },
new SelectListItem { Value = "Percent", Text = "Percent" },
}
};
return model;
}
[HttpPost]
public ActionResult PostValues(CrossFieldValidation model1)
{
model1 = NewMethod();
if (!ModelState.IsValid)
{
return View(model1);
}
else
{
return RedirectToAction("Index");
}
}
}
and this is my view
#model MvcSampleApplication.Models.CrossFieldValidation
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
{
#Html.ValidationSummary(true)
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownListFor(m=> m.SelectedValue , Model.Items)
<input id="PostValues" type="Submit" value="PostValues" />
}
would any one pls help on this...
This line
return View(model1);
looks for the view named exactly like the action in which it was called. Calling this line from PostValues action assumes there is a view PostValues.cshtml (which apparently does not exist). If you still want to use view Index - you should specify this explicitly:
if (!ModelState.IsValid)
{
return View("Index", model1);
}
As Andrei said. Alternatively, you can give your PostValues method an additional tag:
[HttpPost, ActionName("Index")]
public ActionResult PostValues(CrossFieldValidation model1)
{
if (!ModelState.IsValid)
{
return View(model1);
}
}
I've got a form that has a dropDownlist using the Model to fill the list, the view is rendered. The issue is that when i press the submit button, a null pointer exception for Model is thrown. I want to receive the value selected in the Post Action.
Here is my code:
Model:
public class BillViewModel
{
public List<SelectListItem> ClientList { get; set; }
public int SelectedClient { get; set; }
}
Controller Action:
public ActionResult Index()
{
var billRepo = new BillRepo();
var bill = new BillViewModel {ListProducts = billRepo.GetAllProducts()};
bill.ClientList = new List<SelectListItem>();
List<Client> allClientList = billRepo.GetAllClients();
foreach (Client client in allClientList)
{
var item = new SelectListItem() { Value = client.ClientId.ToString(), Text = client.Name };
bill.ClientList.Add(item);
}
ViewBag.ClientSelect = new SelectList(billRepo.GetAllClients(), "value", "text", bill.SelectedClient);
bill.SelectedClient = 1;
return View(bill);
}
[HttpPost]
public ActionResult Index(BillViewModel billViewModel)
{
return View();
}
View: this is where I get the null pointer exception in Model.ClientList
#using (Html.BeginForm())
{
#Html.DropDownListFor(item => item.SelectedClient, Model.ClientList, "Select Client")
<input type="submit" value="Aceptar"/>
}
In the [HttpPost] action method, you are invoking the View() method without any viewmodel. Therefore the Model property inside the view is null. The solution is simply to invoke View and passing in the BillViewModel.
Ex:
[HttpPost]
public ActionResult Index(BillViewModel billViewModel)
{
return View(billViewModel);
}
As the error is trying to tell you, Model.ClientList is null.
You need to initialize the model, just like you did in the GET action. (for example, by calling the same function)
I'm trying to pass the selected value of a DropDownList to a new controller method. However, in the controller, leagueKey is always coming back null. The drop down list is populating with values.
If I change new { leagueKey = Model.SelectedLeagueKey} to new {leagueKey = "test"} the controller correct receives the "test" value. It appears that the DropDownList isn't binding the selected value to Model.SelectedLeagueKey.
Model
public Dictionary<string, string> Leagues { get; set; }
public string SelectedLeagueKey { get; set; }
View
<div class="edit-field">
#Html.DropDownListFor(model => model.SelectedLeagueKey, new SelectList(Model.Leagues, "Key", "Value", Model.SelectedLeagueKey),"Select League")
</div>
#Html.ActionLink("Select League", "AddTeam", "Team", new { leagueKey = Model.SelectedLeagueKey}, null)
Controller
public ActionResult AddTeam(LTEDContext context, string leagueKey)
{
//Do something with leagueKey here
return View();
}
Your view send you the SelectedLeagueKey parameter according to
<div class="edit-field">
#Html.DropDownListFor(model => model.SelectedLeagueKey, new SelectList(Model.Leagues, "Key", "Value", Model.SelectedLeagueKey),"Select League")
</div>
Try to use the next code in a view:
#using (Html.BeginForm("AddTeam", "Team")) {
<div class="edit-field">
#Html.DropDownListFor(model => model.SelectedLeagueKey, new SelectList(Model.Leagues, "Key", "Value", Model.SelectedLeagueKey),"Select League")
</div>
<submit type="submit"/>
}
and the next one in controller:
public ActionResult AddTeam(LTEDContext context, string SelectedLeagueKey)
{
//Do something with leagueKey here
return View();
}