Call HttpPost with Ajax.BeginForm not work - c#

I tried to call method from controller with Ajax, but it never enters the method, i'm import unobtrusive and validate in Bundle, and always refresh all the page. I'm first time in C# i use vb.net, maybe it's a basical error, but i search a lot and try diferent ways and nothing. thanks for ur time and i hope someone can help me
Update: i have a form inside Master page and that generate the problem D:
View
#model PlanificacionOperacional.Models.FiltroView
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Styles
{
#Styles.Render("https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css")
#Styles.Render("https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css")
}
<div class="card-header header-elements-inline" style="padding-top:0;"><h4 class="card-title">Muestreos</h4></div>
<fieldset>
#using (Ajax.BeginForm("Filtrar", "Muestreo",
new AjaxOptions
{
UpdateTargetId = "tabless",
HttpMethod = "POST"
}))
{
<div class="form-group">
#Html.DropDownListFor(model => model.predio, new SelectList(ViewBag.formularios, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Predio" })
#Html.DropDownListFor(model => model.zona, new SelectList(ViewBag.zonas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Zona" })
#Html.DropDownListFor(model => model.area, new SelectList(ViewBag.areas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Area" })
</div>
<div class="form-group" style="align-self:center;">
#*<input type="submit" value="Filtrar" class="btn btn-primary" style="width:150px;" />*#
<button type="submit">Filtrar</button>
</div>
}
</fieldset>
<div id="tabless" class="card-body" style="">
<table id="table_id" class="display">
<thead>
<tr>
<th></th>
<th>ID Muestro</th>
<th>Area</th>
<th>Id Predio</th>
<th>Predio</th>
<th>Formulario</th>
<th>APLA</th>
<th>Total Parcelas</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.muestreos)
{
<tr>
<td><input type="checkbox" id="cbox2" value="second_checkbox"></td>
<td>#item.IdMuestreo</td>
<td>#item.Area</td>
<td>#item.IdPredio</td>
<td>#item.NomPredio</td>
<td>#item.Formulario</td>
<td>#item.APLA</td>
<td>#item.TotalParcela</td>
</tr>
}
</tbody>
</table>
</div>
#section JavaScriptToFooter {
#Scripts.Render("https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js")
#Scripts.Render("https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js")
<script>
$(document).ready(function () {
$('#table_id').DataTable();
$('.selectpicker').selectpicker();
});
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PlanificacionOperacional.Models;
using PlanificacionOperacional.Repository;
namespace PlanificacionOperacional.Controllers
{
public class MuestreoController : Controller
{
// GET: Muestreo
public ActionResult Index()
{
MuestreoRepository muestreo = new MuestreoRepository();
List<Muestreo> muestreos = muestreo.TraeMuestreo();
List<Filtro> predios = muestreo.TraePredios();
List<Filtro> zonas = muestreo.TraeZonas();
List<Filtro> areas = muestreo.TraeAreas();
ViewBag.muestreos = muestreos;
ViewBag.formularios = predios;
ViewBag.zonas = zonas;
ViewBag.areas = areas;
return View();
}
[HttpPost]
public ActionResult Filtrar(FiltroView model)
{
int predio = Convert.ToInt32(Request["predio"].ToString());
int zona = Convert.ToInt32(Request["zona"].ToString());
return View();
}
// GET: Muestreo/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Muestreo/Create
public ActionResult Create()
{
return View();
}
// POST: Muestreo/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Muestreo/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Muestreo/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Muestreo/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Muestreo/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PlanificacionOperacional.Models
{
public class FiltroView
{
public int zona { get; set; }
public long predio { get; set; }
public int area { get; set; }
}
}

You are using MVC but you dont have any model. You will never be able to submit form without model. So for the start create a model
public ViewModel
{
public int ZonaId {get; set;]
public int AreaId {get;set;}
.... and so on
}
and after this view
#model ViewModel
......
#Html.DropDownListFor(model=>model.PredioId, new SelectList(ViewBag.formularios, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Predio" })
#Html.DropDownListFor(model=>model.ZonaId, new SelectList(ViewBag.zonas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Zona" })
#Html.DropDownListFor(model=>model.AreaId, new SelectList(ViewBag.areas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Area" })
.... and so on
action
public ActionResult Filtrar(ViewModel model)
{
int predioId = model.PredioId;
int zonaId = model.ZonaId;
.... your code
}
PS.
Get rid of all your viewbags. It looks very unprofessionaly and it is hard to mantain this kind of code. Include everything in the ViewModel.
public ActionResult Index()
{
MuestreoRepository muestreo = new MuestreoRepository();
var model=new ViewModel{
muestreos = muestreo.TraeMuestreo(),
predios = muestreo.TraePredios();
zonas = muestreo.TraeZonas();
areas = muestreo.TraeAreas();
....and so on
}
return View(model);
}

Related

Add an object from a View (Passing from View to Controller)

I'm working in a C# project. In my ReglasDispositivos view there are three diferent actions which a client can do: add a device, update a device and delete once. The controller calls ReglasDispositivos() (get) view passing a ClienteReglasDispositivos model. Lets go, for example, to adding a device. How can i post the info that the client is posting?
If my view only have one action, I know that I have to add in the controller [HttpPost] and [HttpGet] ReglasDispositivos() method. But when a view has three diferentes actions?
ClientController:
[HttpGet]
public ActionResult ReglasDispositivos()
{
ClienteReglasDispositivos model = new ClienteReglasDispositivos();
return View(model);
}
ReglasDispositivos view (Adding a device parte) (Im not sure about that BeginForm):
#model SistemaGestion.Models.ClienteReglasDispositivos
...
<div class="view-tables">
<div id="myAdd" class="div-table">
#using (Html.BeginForm("AgregarDispositivo", "Client", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<fieldset class="fieldset-box">
<div class="editor-field">
#Html.TextBoxFor(model => model.NombreDispositivo, new { Class = "YourBackgroundClass", Placeholder = "Nombre del dispositivo" });
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.HorasDeUso, new { Class = "YourBackgroundClass", Placeholder = "KwPorHora" });
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.EsInteligente, new { Class = "YourBackgroundClass" });
</div>
<input type="submit" class="submit-login" value="AGREGAR" />
</fieldset>
}
</div>
ClienteReglasDispositivos
public class ClienteReglasDispositivos
{
[Required]
public string NombreDispositivo { get; set; }
[Display(Name = "Es inteligente?")]
public bool EsInteligente { get; set; }
public double KwPorHora { get; set; }
public float HorasDeUso { get; set; }
public string Condicion { get; set; }
}
You can have multiple actions with identical name due to polymorphysm. Asp decide what action you call by [Http(XX)].
You can have
[HttpGet]
public ActionResult ReglasDispositivos()
{
ClienteReglasDispositivos model = new ClienteReglasDispositivos();
return View(model);
}
[HttpPost]
public ActionResult ReglasDispositivos([FromForm] ClienteReglasDispositivos model)
{
if(ModelState.IsValid(model)) {
//do something
}
return View(model);
}
Also you can call different action name and return same view
[HttpGet]
public ActionResult ReglasDispositivos()
{
ClienteReglasDispositivos model = new ClienteReglasDispositivos();
return View(model);
}
[HttpPost]
public ActionResult ReglasDispositivosPost([FromForm] ClienteReglasDispositivos model)
{
return View("ReglasDispositivos", model);
}
Read more

Retrieving ViewModel with multiple list objects once its posted

I have a viewmodel class like this:
public class ViewModel
{
public string VendorService { get; set; }
public List<ResponseView> responseList { get; set; }
}
Controller has get and post edit actions:
public ActionResult Edit(int? id)
{
List<ResponseView> resp = getResponseView(id); //get the list of ResponseView objects.
ViewModel view = new ViewModel();
view.responseList = resp;
view.VendorService = "Car Manufacturer";
return View(view);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel view)
{
if (ModelState.IsValid)
{
List<ResponseView> respList = new List<ResponseView>();
respList = view.responseList;
foreach(ResponseView resp in respList)
{
Debug.WriteLine(resp.Question);
}
return RedirectToAction("editConfirm");
}
return View("Index");
}
Edit.cshtml
#model Tools.Models.ViewModel
#{
List<Tools.Models.ResponseView> respList= Model.responseList as List<Tools.Models.ResponseView;
}
#foreach (var item in respList)
{
<div class="col-md-5">
#Html.EditorFor(model => item.Response, "" } })
#Html.ValidationMessageFor(model => item.Response, "", "" })
</div>
}
I am able to display the view and all the data in the View Model as required. But I am getting a null pointer reference when I try to retrieve the response in my post action, on foreach line below.
List<ResponseView> respList = new List<ResponseView>();
respList = view.responseList;
foreach(ResponseView resp in respList)
{
Debug.WriteLine(resp.Response);
}
You have to use for instead foreach . Please try this,
#for (int i = 0; i < Model.responseList.Count; ++i) {
<div>
#Html.EditorFor(model => Model.responseList[i].Response, "")
</div>

How can i set the value of my textbox using radio button?

this is my controller view
public ActionResult rb()
{
subject ts = new subject();
ts.subjectlist = db.tbSubjs.ToList();
ts.selectsubj = "";
return View(ts);
}
[HttpPost]
public ActionResult rb(subject sj, FormCollection frm)
{
if (ModelState.IsValid)
{
var selectsubj = sj.selectsubj;
string getcode = frm["subj"];
ViewBag.ssss = getcode;
}
return View("Index");
}
and this is my class
public class subject
{
public List<tbSubj> subjectlist { get; set; }
public string selectsubj { get; set; }
}
Here is my code for the radio button
<div style="text-align: left">
#using (Html.BeginForm("rb", "Home"))
{
<div>------</div>
foreach (var ts in Model.subjectlist)
{
<div>
#Html.Label(ts.SubjCode)
#Html.RadioButtonFor(m => m.subjectlist, ts.SubjCode)
</div>
}
foreach (var getsubj in Model.subjectlist)
{
<div>------------------</div>
<div>
#getsubj.SubjCode
#Html.RadioButton("subj", getsubj.SubjCode)
</div>
}
<br />
<input id="Submit" type="submit" value="Submit" />
}
</div>
and i want to set a value in my textbox in this view by getting the value of my radio button.
#model ATM.Models.subject
#{
ViewBag.Title = "rb";
}
<h2>rb</h2>
#Html.TextBox(m => m.selectsubj)
If someone is willing to help me please help me.
Assuming that your action actually looks more like the following:
[HttpPost]
public ActionResult rb(subject sj, FormCollection frm)
{
if (ModelState.IsValid)
{
var selectsubj = sj.selectsubj;
string getcode = frm["subj"];
ViewBag.ssss = getcode;
return View("view_with_textbox");
}
return View("Index");
}
You could do this:
[HttpPost]
public ActionResult rb(subject sj, FormCollection frm)
{
if (ModelState.IsValid)
{
var selectsubj = sj.selectsubj;
string getcode = frm["subj"];
var model = new ATM.Models.subject()
{
selectsubj = getcode
};
return View("view_with_textbox", model);
}
return View("Index");
}
Thereby passing the value in via the model.

C# Razor trying to populate textbox from Dropdown

I am trying to build a EF C# Razor application. I continue to fail in endeavor to have the dropdown box[listbox]'s choice call a route called getRecruiter(with that value) and change the recruitername textbox to the recruiter.
It errors saying: Uncaught ReferenceError: RecruiterName is not defined
If anyone could help me, I would greatly appreciate it. I am trying to learn how to use Razor and C# and have tried everything I could find online.
Here is the relevant code:
Notes Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace JOM.Models
{
public class NotesModel
{
[Key]
public int NotesID { get; set; }
public int JobID { get; set; }
public string Recruiter { get; set; }
public string NoteTitle { get; set; }
public string NoteData { get; set; }
public DateTime ActiveDate { get; set; }
}
public class JobWithRecruiter
{
public int JobID { get; set; }
public string RecruiterName { get; set; }
}
}
Notes Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using JOM.DAL;
using JOM.Models;
namespace JOM.Controllers
{
public class NotesModelsController : Controller
{
private JobsContext db = new JobsContext();
// GET: NotesModels
public ActionResult Index()
{
IEnumerable<JobModel> jobs = db.Jobs;
ViewData["jobs"] = jobs;
return View(db.Notes.ToList());
}
// GET: NotesModels/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NotesModel notesModel = db.Notes.Find(id);
if (notesModel == null)
{
return HttpNotFound();
}
return View(notesModel);
}
// GET: NotesModels/Create
public ActionResult Create()
{
IEnumerable<JobModel> jobs = db.Jobs;
ViewData["jobs"] = jobs;
return View();
}
// POST: NotesModels/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "NotesID,JobID,Recruiter,NoteTitle,NoteData,ActiveDate")] NotesModel notesModel)
{
ViewBag.Jobs =
from job in db.Jobs
select job;
ViewBag.Recruiters =
from job in db.Jobs
join note in db.Notes on job.JobID equals note.JobID
select new JobWithRecruiter { JobID = job.JobID, RecruiterName = note.Recruiter };
if (ModelState.IsValid)
{
db.Notes.Add(notesModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(notesModel);
}
// GET: NotesModels/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NotesModel notesModel = db.Notes.Find(id);
if (notesModel == null)
{
return HttpNotFound();
}
return View(notesModel);
}
// POST: NotesModels/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "NotesID,JobID,Recruiter,NoteTitle,NoteData,ActiveDate")] NotesModel notesModel)
{
if (ModelState.IsValid)
{
db.Entry(notesModel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(notesModel);
}
// GET: NotesModels/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NotesModel notesModel = db.Notes.Find(id);
if (notesModel == null)
{
return HttpNotFound();
}
return View(notesModel);
}
// POST: NotesModels/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
NotesModel notesModel = db.Notes.Find(id);
db.Notes.Remove(notesModel);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Notes View:
#model JOM.Models.NotesModel
#using JOM.Models;
#{
ViewBag.Title = "Create";
}
#functions
{
public string getRecruiter(int jobID)
{
if (jobID > 0)
{
var j = (IEnumerable<JobWithRecruiter>)ViewBag.Recruiters;
return j.Where(jo => jo.JobID.Equals(jobID)).First<JobWithRecruiter>().RecruiterName;
}
return "No Name Selected";
}
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Notes</h4>
<hr />
#{
int selectedJobID = 0;
string RecruiterName = "Not Selected";
}
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-2" for="JobDesc">Choose Job:</label>
<div class="col-md-10">
#{
var jobs = (IEnumerable<JobModel>)ViewBag.Jobs;
}
#Html.DropDownList("listbox", jobs.Select(item => new SelectListItem
{
Value = item.JobID.ToString(),
Text = item.JobDesc.ToString()
}))
<script language="Javascript">
$(document).ready(function () {
$('#listbox').change(function () {
selectedJobID = $(this).val();
#{
RecruiterName = getRecruiter(selectedJobID);
}
$('#recruiter').val(RecruiterName);
});
});
</script>
</div>
</div>
<div class="form-group">
#Html.Label("Recruiter", htmlAttributes: new {#class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox(RecruiterName, RecruiterName,new { ID="recruiter", #class = "form-control" });
#Html.ValidationMessageFor(model => model.Recruiter, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NoteTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NoteTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NoteTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NoteData, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NoteData, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NoteData, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ActiveDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActiveDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActiveDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
You can't invoke C# code like if it was JS code, so this
$(document).ready(function () {
$('#listbox').change(function () {
selectedJobID = $(this).val();
#{
RecruiterName = getRecruiter(selectedJobID);
}
$('#recruiter').val(RecruiterName);
});
});
doesn't mean RecruiterName = getRecruiter(selectedJobID); will be assigned when you change value of #listbox dropdown.
What you could do is preparing JSON collection containing all your recruiters inside controller and pass it to your view. Then you could use only JS (which would work used like you tried with C# code) to retrieve recruiters name based on ID.
In controller invoke list:
[HttpPost]
public ActionResult bindCityList(int stateid)
{
List<SelectListItem> lstcity = new List<SelectListItem>();
try
{
Panel cs = new Panel();
DataTable dt = new DataTable();
dt = cs.getCityVsState(Conn, stateid);
foreach (System.Data.DataRow dr in dt.Rows)
{
lstcity.Add(new SelectListItem { Text = #dr["CityName"].ToString(), Value = #dr["CityID"].ToString() });
}
}
catch (Exception ex)
{
logger.WriteErrorToFile("Panel::bind City List :" + ex.Message.ToString());
}
finally
{
Conn.Close();
}
return Json(lstcity.AsEnumerable());
}
In view --
On change of state dropdown bind city list
$('#ddlstate').change(function () {
var url = "bindCityList";
$.ajax({
url: url,
data: { stateid: $('#ddlstate').val() },
cache: false,
type: "POST",
success: function (data) {
$("#ddlcity").empty();
var markup = "<option value='0'>---Select---</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value='" + data[x].Value + "'>" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});

MVC4 Validate Item Selected In DropDownList

I have a page to create objects, and in this I have a DropDownList. If I select an item from the list my page will save correctly, however if I don't select an item it looks like it fails on a postback as the objects will be null.
What I want is to try and validate whether the user has selected an item (default is "Please Select...").
I have code that will check and see in the controller if the item is null, but it's how do I then display a message? Keeping all other details if they exist.
public ActionResult Create(int objectId = 0)
{
var resultModel = new MyObjectModel();
resultModel.AllObjects = new SelectList(_system.GetAllObjects(objectId));
// GetAllObjects juts returns a list of items for the drop down.
return View(resultModel);
}
[HttpPost]
public ActionResult Create(int? objectId, FormCollection collection)
{
try
{
int objectIdNotNull = 0;
if (objectId > 1)
{
objectIdNotNull = (int) objectId;
}
string objectName = collection["Name"];
int objectTypeSelectedResult = 1;
int.TryParse(collection["dllList"], out objectTypeSelectedResult);
if (!Convert.ToBoolean(objectTypeSelectedResult))
{
// So here I have discovered nothing has been selected, and I want to alert the user
return RedirectToAction("Create",
new {ObjectId = objectIdNotNull, error = "Please select an Object Type"});
}
....
return RedirectToAction(...)
}
catch
{
return View();
}
}
The above code just goes to the Create page but doesn't display an error. In my View for Create I have the following line which I assumed would display any errors:
#ViewData["error"]
Additional code
Model:
using System.Collections.Generic;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace MyNameSpace
{
public class MyObjectModel
{
[Required(ErrorMessage = "Please select an Object Type")]
public SelectList AllObjects { get; set; } // I populate the drop down with this list
}
}
View:
#model MyNameSpace.MyObjectModel
#{
ViewBag.Title = "Create";
}
<h2>Create </h2>
<p class="text-error">#ViewData["Message"]</p>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"> </script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.MyObject.Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(model=>model.MyObjectType.Name, new {style="width: 750px"})
#Html.ValidationMessageFor(model => model.MyObjectType.Name)
</div>
<div>
<label for="ddlList">Choose Type</label>
#if (#Model != null)
{
#Html.DropDownList("ddlList", Model.AllObjects, "Please Select...")
#Html.ValidationMessageFor(model => model.AllObjects, "An object must be selected", new { #class = "redText"})
}
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
You are validating the SelectList which is wrong
[Required(ErrorMessage = "An object must be selected")]
public SelectList AllObjects { get; set; }
Your Model should be
[Required(ErrorMessage = "Please select an Object Type")]
public int ObjectId { get; set; }
public string ObjectName { get; set; }
Your Controller(no need for form collection thats the whole point of MVC)
public ActionResult Create(int Id = 0)
{
MyObjectModel resultModel = new MyObjectModel();
var ObjectResultList = _system.GetAllObjects(Id);
var ObjectSelectList = new SelectList(ObjectResultList, "id", "Name");
ViewBag.ObjectList = ObjectSelectList;
return View(resultModel);
}
Your Post controller:
[HttpPost]
public ActionResult Create(MyObjectModel o)
{
try
{
if (ModelState.IsValid)
{
//It's valid , your code here!
return RedirectToAction("ObjectCreated", new { id = o.objectId });
}
else
{
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
}
}
}
catch (Exception ex)
{
Response.Write(ex.InnerException.Message);
}
//If we get here it means the model is not valid, We're in trouble
//then redisplay the view repopulate the dropdown
var ObjectResultList = _system.GetAllObjects(objectId);
var ObjectSelectList = new SelectList(ObjectResultList, "id", "value");
ViewBag.ObjectList = ObjectSelectList;
return View(o);
}
Your View should be strongly Typed
<div class="editor-label">
#Html.LabelFor(model => model.ObjectId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ObjectId,
(IEnumerable<SelectListItem>)ViewBag.ObjectList, "-- Select One Object --")
#Html.ValidationMessageFor(model => model.ObjectId)
</div>

Categories

Resources