I have created a form and i am using validation on it but whenever i click on submit it not redirect and shows the same page.Even i have set the default values then also no help.
please help me.
Even i have check on varuious form no help.
registration form class
class registrationform extends sfForm {
//put your code here
protected static $option=array('Lab Technician','Lecturur','Assistant Professor','Professor','H.O.D');
public function configure() {
$this->setWidgets(array(
'first_Name'=>new sfWidgetFormInputText(array('default'=>'hello'),array('class' => 'textView'),array('default'=>'hello')),
'middle_Name'=>new sfWidgetFormInputText(array('default'=>'hello'),array('class' => 'textView')),
'last_Name'=>new sfWidgetFormInputText(array('default'=>'hello'),array('class'=>'textView')),
'age'=>new sfWidgetFormInputText(array('default'=>'hello'),array('class'=>'textView')),
));
$this->setValidators(array(
'first_Name' => new sfValidatorString(array('required' => 'The message field is required.')),
'middle_Name' => new sfValidatorString(array('required' => 'The message field is required.')),
'last_Name' => new sfValidatorString(array('required' => 'The message field is required.')),
'age' => new sfValidatorString(array('required' => 'The message field is required.')),
));
$this->widgetSchema->setNameFormat('contact[%s]');
}
****action.class.php****
this is a class i which i am having my action class code.
public function executeIndex(sfWebRequest $request)
{
// $this->forward('default', 'module');
$this->registration_form = new registrationform();
if ($request->isMethod('POST'))
{
$this->registration_form->disableLocalCSRFProtection();
$this->registration_form->bind($request->getParameter('contact'));
if (!($this->registration_form->isValid()))
{
echo"\hiol";
$this->redirect('registration/thankyou?'.http_build_query($this->registration_form->getValues()));
}
}
indexsuccess
<?php echo stylesheet_tag('form');?>
<div class="page">
<div class="form" >
<form action="<?php echo url_for('registration/index') ?>" method="POST">
<div class="row" id="head">
REGISTRATION FORM
</div>
<div class="row">
<div class="columnLabel"><?php echo $registration_form['first_Name']->renderLabel()?></div>
<div class="columnView"><?php echo $registration_form['first_Name']->render()?></div>
</div>
<div class="row">
<div ><?php echo $registration_form['first_Name']->renderError()?></div>
</div>
<div class="row">
<div class="columnLabel" ><?php echo $registration_form['middle_Name']->renderLabel()?></div>
<div class="columnView" ><?php echo $registration_form['middle_Name']->render()?></div>
</div>
<div class="row">
<div class="columnLabel"><?php echo $registration_form['last_Name']->renderLabel()?></div>
<div class="columnView"><?php echo $registration_form['last_Name']->render()?></div>
</div>
<div class="row">
<div class="columnLabel"><?php echo $registration_form['age']->renderLabel()?></div>
<div class="columnView"><?php echo $registration_form['age']->render()?></div>
</div>
<div class="row">
<div class="columnLabel"><input class="button" type="submit" value="submit" name="submit"></div>
</div>
</form>
</div>
<!-- </div>
</div>
</div>
</div>
</div>-->
Your action class is not saving the form if it's valid. You should save and redirect if the form is valid:
if ($this->registration_form->isValid())
{
$this->registration_form->save();
$this->redirect('registration/thankyou');
}
If you need the form value on the next page, don't pass them in url, but flash instead:
$this->getUser()->setFlash('registration_form', $this->registration_form->getValues());
Related
I have a ViewModel containing information for an object called ContactEvent. ContactEvent has a boolean called IsActive. I'm using #Html.CheckBoxFor() for a checkbox to let the user alter its value. The problem is that if the value is originally true and the user sets it to false, the model passed through the POST has the updated value. But if the value is originally false, the model passed through the POST always returns false still. I have no idea what is causing it.
View
#model ContactEventViewModel
#{
ViewBag.Title = "Contact Event";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<head>
<script src="~/datatables/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="~/datatables/css/jquery.dataTables.min.css" />
</head>
<body>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
#using (Html.BeginForm("ContactEvent", "ContactEvents", FormMethod.Post))
{
<h1>Edit Contact Event</h1>
#Html.HiddenFor(Model => Model.ContactEvent.ContactEventSysID, new { #Value = Model.ContactEvent.ContactEventSysID })
<div class="form-group row">
<label>Customer</label>
<div class="col-md-7 col-lg-7">
<Label>#String.Format("{1}, {0}", Model.Customer.FirstName, Model.Customer.LastName)</Label>
#Html.HiddenFor(Model => Model.Customer.CustomerSysID, new { #Value = Model.Customer.CustomerSysID })
</div>
</div>
<div class="form-group row">
<label>Date</label>
<div class="col-md-7 col-lg-7">
#Html.EditorFor(model => model.ContactEvent.Date, new { htmlAttributes = new { #class = "datepicker", #Name = "date", #PlaceHolder = "mm/dd/yyyy" } })
</div>
</div>
<div class="form-group row">
<label>Event Type</label>
<div class="col-md-7 col-lg-7">
#Html.DropDownListFor(Model => Model.ContactEvent.ContactEventTypeSysID, new SelectList(Model.ListOfContactEventTypes, "ContactEventTypeSysID", "Description"))
</div>
</div>
<div class="form-group row">
<label>Outcome</label>
<div class="col-md-7 col-lg-7">
#Html.DropDownListFor(Model => Model.ContactEvent.OutcomeSysID, new SelectList(Model.ListOfOutcomes, "OutcomeSysID", "Description"))
</div>
</div>
<div class="form-group row">
<label>Note</label>
<div class="col-md-7 col-lg-7">
#Html.TextBoxFor(Model => Model.ContactEvent.Note, new { #Value = Model.ContactEvent.Note })
</div>
</div>
<div class="form-group row">
<label>Created Date</label>
<div class="col-md-7 col-lg-7">
<label>#Model.ContactEvent.CreatedDate</label>
</div>
</div>
<div class="form-group row">
<label>Last Updated Date</label>
<div class="col-md-7 col-lg-7">
<label>#Model.ContactEvent.LastUpdatedDate</label>
</div>
</div>
<div class="form-group row">
<label>Active?</label>
<div class="col-md-7 col-lg-7">
#Html.CheckBoxFor(Model => Model.ContactEvent.IsActive, new { #Value = Model.ContactEvent.IsActive })
</div>
</div>
<input type="submit" id="updateButton" value="Submit" />
}
</div>
</body>
Method in Controller
[HttpPost]
public IActionResult ContactEvent(ContactEventViewModel contactEventViewModel)
{
if (ModelState.IsValid)
{
string connectionString = Startup.ConnectionString;
string query = "UPDATE [CRM].[dbo].[ContactEvent] " +
"SET [Date]=#Date, [ContactEventTypeSysID]=#ContactEventTypeSysID, [OutcomeSysID]=#OutcomeSysID, [Note]=#Note, [LastUpdatedDate]=#LastUpdatedDate, [IsActive]=#IsActive " +
"WHERE [ContactEventSysID]=#ContactEventSysID";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#Date", contactEventViewModel.ContactEvent.Date);
command.Parameters.AddWithValue("#ContactEventTypeSysID", contactEventViewModel.ContactEvent.ContactEventTypeSysID);
command.Parameters.AddWithValue("#OutcomeSysID", contactEventViewModel.ContactEvent.OutcomeSysID);
if (contactEventViewModel.ContactEvent.Note == null)
{
command.Parameters.AddWithValue("#Note", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("#Note", contactEventViewModel.ContactEvent.Note);
}
command.Parameters.AddWithValue("#LastUpdatedDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
command.Parameters.AddWithValue("#IsActive", contactEventViewModel.ContactEvent.IsActive);
command.Parameters.AddWithValue("#ContactEventSysID", contactEventViewModel.ContactEvent.ContactEventSysID);
connection.Open();
command.ExecuteNonQuery();
}
}
}
return RedirectToAction("ContactEvent", "ContactEvents", new { ContactEventSysID = contactEventViewModel.ContactEvent.ContactEventSysID });
}
Let me know if you need any other code. Thanks in advance.
Please remove #Value = Model.ContactEvent.IsActive. This will let your model properly handle the value. Do not set any values unless you are sure, that you want to override model behavior.
I am buidling a mvc web application with entity framework.
Error:
An exception of type 'System.ObjectDisposedException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: The ObjectContext instance has been disposed
and can no longer be used for operations that require a connection.
This is the entity framework part:
Like you see I already include "Alineas" and do .ToList()
public IList<Kop> Handle(RetrieveKoppenForDocumentQuery query)
{
using (var db = new BmDataContext())
{
var koppen = db.Kop.Where(s => s.Document.Id == query.Id)
.Include(s => s.TegelAfbeelding)
.Include(s => s.CollageAfbeeldingen)
.Include(s => s.FinancieleAfbeeldingen)
.Include(s => s.Alineas)
.ToList();
return _orderKoppenByIndex(koppen);
}
}
This is the view KopListItems.cshtml:
#using PGE.Bestuursmonitor.Contracts.DataTypes
#model IList<Kop>
#* Helper for recursively rendering koppen*#
#helper SortableItem(Kop kop)
{
<div class="sortable-item" data-kopid="#kop.Id">
<div class="row">
<div class="col-md-7 title-column">
<i class="fa fa-arrows"></i> #kop.Titel
</div>
<div class="col-md-5">
<div class="col-md-3">
<span>
#kop.KopType
</span>
</div>
<div class="col-md-3">
<span>
#kop.Status
</span>
</div>
<div class="col-md-6">
<span class="pull-right">
#if (#kop.Alineas != null) // on this line I receive the exception
{
// here I would like to do some logic
}
</span>
</div>
</div>
</div>
<div class="sortable-container">
#foreach (var subKop in kop.Koppen)
{
#SortableItem(subKop);
}
</div>
</div>
}
#* Recursively render all kop items *#
<div id="koppen_sortable" class="sortable-container">
#foreach (Kop kop in Model)
{
#SortableItem(kop);
}
</div>
This is the view KoppenList.cshtml:
#model PGE.Bestuursmonitor.ViewModels.Koppen.IKoppenListViewModel
<h1>#Model.DocumentTitel</h1>
#* Render kop list header *#
<div id="koppen_sortable_header">
<div class="row">
<div class="col-md-7"><strong>Titel</strong></div>
<div class="col-md-5">
<div class="col-md-3">
<strong>Type</strong>
</div>
<div class="col-md-3">
<strong>Status</strong>
</div>
<div class="col-md-6">
<span class="pull-right">
<button type="button" id="btn_add_sub" class="btn btn-success" title="Kop aanmaken" role="button" onclick="BM.Koppen.LoadAddKopView(null);">
<i class="fa fa-plus fa-lg"></i> Kop aanmaken
</button>
</span>
</div>
</div>
</div>
</div>
<div id="koppen_sortable_body">
#{ Html.RenderPartial("~/Views/Koppen/KopListItems.cshtml", #Model.Koppen); }
</div>
#* Store document id in html DOM, so javascript can reach it from multiple places *#
<input type="hidden" id="document_id" value="#Model.DocumentId" />
Action in controller:
[HttpGet]
public ActionResult KoppenList(string id)
{
ViewBag.PageId = id;
Document document = _retrieveStartPcDocumentQueryHandler.Handle(new RetrieveStartPcDocumentQuery());
RetrieveKoppenForDocumentQuery query = new RetrieveKoppenForDocumentQuery
{
Id = document.Id
};
IList<Kop> koppen = _retrieveKoppenForDocumentQueryHandler.Handle(query);
_koppenListViewModel.Koppen = koppen;
_koppenListViewModel.DocumentTitel = document.Titel;
_koppenListViewModel.DocumentId = document.Id;
return View("~/Views/Koppen/KoppenList.cshtml", _koppenListViewModel);
}
Like you see in KopListItems.cshtml there are 2 foreach loops. The outer foreach loop is working fine and can read "Alineas". The inner foreach which shows the sub items gives this strange error. What is going wrong? Im stuck.
This is the solution. You need to get the alineas and content also on sub level:
public IList<Kop> Handle(RetrieveKoppenForDocumentQuery query)
{
using (var db = new BmDataContext())
{
var koppen = db.Kop.Where(s => s.Document.Id == query.Id)
.Include(s => s.TegelAfbeelding)
.Include(s => s.CollageAfbeeldingen)
.Include(s => s.FinancieleAfbeeldingen)
.Include(s => s.Alineas.Select(a => a.Content))
.Include(s => s.Koppen.Select(k => k.Alineas.Select(a => a.Content)))
.Include(s => s.Koppen.Select(k => k.Koppen.Select(x => x.Alineas.Select(a => a.Content))))
.ToList();
return _orderKoppenByIndex(koppen);
}
}
I'm working with MVC and spent whole day getting stuck with this problem. Here is code at the controller:
public class CMController : Controller
{
public ActionResult SignUp()
{
return View("SignUpPage");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignUp(User u)
{
if (ModelState.IsValid)
{
using (CmdbEntities dc = new CmdbEntities())
{
dc.Users.Add(u);
dc.SaveChanges();
ModelState.Clear();
u = null;
ViewBag.Message = ("Successfully sign on");
}
}
else
{
ViewBag.Message = ("Error");
}
return View("Welcome");
}
}
Here is the SignUpPage.cshtml view:
#using (Html.BeginForm("SignUp", "CM", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-group" style="padding:5px 50px">
<label> First name:</label>
<div>
#Html.TextBoxFor(model => model.FirstName, new {#class="form-control", placeholder="Enter first name", ID="FirstName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label >Last name:</label>
<div>
#Html.TextBoxFor(model => model.LastName, new {#class="form-control", placeholder="Enter first name", ID="LastName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="email">Email:</label>
<div>
#Html.TextBoxFor(model => model.Email, new {#class="form-control", placeholder="Enter email", ID="Email", type="email"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label >User name:</label>
<div>
#Html.TextBoxFor(model => model.UserName, new {#class="form-control", placeholder="Enter user name", ID="UserName"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="pwd">Password:</label>
<div>
#Html.TextBoxFor(model => model.Password, new {#class="form-control", placeholder="Enter password", ID="Password", type="password"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<label for="pwd">Confirm password:</label>
<div>
#Html.TextBoxFor(model => model.ConfirmPassword, new {#class="form-control", placeholder="Re-enter password", ID="_password", type="password"})
</div>
</div>
<div class="form-group" style="padding:5px 50px">
<div>
<input type="submit" ID="SignUp" class="btn btn-success" value="Sign Up" />
</div>
</div>
}
The problem is, when load page first time, the action SignUp() is called which is correct. But when submit the form, SignUp() is called again instead of the post action SignUp(User u).
One more problem, even the form has post method, when click submit the url contains input information just like get method, I don't understand.
Here is the page html source of form tag.
<form action="/CM/SignUp" method="post"><input name="__RequestVerificationToken" type="hidden" value="VJ0YcQr1Z-l3Qo717pRpZNT-QtL59G2EJXy2JQL8NFnOm-XoNnAD-8T-Itz3i1EboGj0bhpBf2G26ifxm4F5ZRyKimkOyZW1AxZ3ckPNuRk1" />
Please help, thank you.
Can you please try adding
[AllowAnonymous]
to the post method?
Did you activate global authorization anywhere
System.Web.Mvc.AuthorizeAttribute
?
In my form I use the DateTimePicker from Kendo UI. When I press the submit button the focus of the DateTimePicker is triggered and not the form submit event.
#using (Html.BeginForm("Edit", "NursingHome", FormMethod.Post, new { #class = "form-horizontal", #role = "form" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.ShortTimeCare, new { #class = "col-xs-4 col-sm-3 col-md-2 col-lg-2 control-label" })
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
#(Html.Kendo().NumericTextBoxFor(model => model.ShortTimeCare)
.Format("n0")
.Min(0)
)
</div>
</div>
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
#(Html.Kendo().DateTimePickerFor(model => model.ShortTimeCareForDate)
.Name("ShortTimeCareForDate")
.Value(DateTime.Now)
.Interval(15)
)
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-4 col-sm-offset-3 col-md-offset-2 col-lg-offset-2 col-xs-10 col-sm-10 col-md-2 col-lg-2">
<button type="submit" class="btn btn-default">Save</button>
</div>
</div>
}
Have I forgotten something?
In my ViewModel I have a DateTime attribute.
public DateTime ShortTimeCareForDate { get; set; }
When I press the submit button the Curser jumps into the DateTimePicker Field. Nothing else happens.
When I change the code as following the submit event works as desired. (Maybe a Problem with the DateTime Attribute in the Model)
<div class="col-xs-2 col-sm-2 col-md-2 col-lg-2">
#(Html.Kendo().DateTimePicker() // For(model => model.ShortTimeCareForDate)
.Name("ShortTimeCareForDateXXXXX")
.Value(DateTime.Now)
.Interval(15)
)
</div>
regards,
Marko
When I use the english dateformat then it works. But I need the german format.
English:
#(Html.Kendo().DateTimePickerFor(model => model.ShortTimeCareForDate)
.Name("ShortTimeCareForDate")
.Value(DateTime.Now)
.Format("yyyy-MM-dd hh:mm:ss")
.Interval(15)
)
German
#(Html.Kendo().DateTimePickerFor(model => model.ShortTimeCareForDate)
.Name("ShortTimeCareForDate")
.Value(DateTime.Now)
.Format("dd.MM.yyyy hh:mm:ss")
.Interval(15)
)
Use button type="button" instead of using submit
<div class="form-group">
<div class="col-xs-offset-4 col-sm-offset-3 col-md-offset-2 col-lg-offset-2 col-xs-10 col-sm-10 col-md-2 col-lg-2">
<button type="button" class="btn btn-default">Save</button>
</div>
</div>
looks like you are using the wrong culture either on the client or on the server side.
according to http://docs.telerik.com/kendo-ui/aspnet-mvc/globalization you have to set the german culture like follows:
include the culture you want to use right under ~/Scripts/cultures/kendo.culture.de-DE.min.js
in your Layout.cshtml include the culture:
<script src="#Url.Content("~/Scripts/cultures/kendo.culture.de-DE.min.js")"></script>
and set it afterwards:
<script>
kendo.culture("de-DE");
</script>
if you want to set the culture on the server side you need to update your web.config like that:
<system.web>
<globalization uiCulture="de-DE" culture="de-DE"></globalization>
</system.web>
this should fix the occurring issue
I have scenario where I have load data on dropdown selection change and after manipulation I have to submit the page for saving.
I have developed the page but since I new to MVC so can anyone verify me code and can suggest better approach of doing the same.
#using (Html.BeginForm("Save", "forecast"))
{
using (Html.BeginForm("YearChange", "forecast", FormMethod.Get, new {#id="frmYearChange" }))
{
<div class="span12">
<div class="well well-sm" style="padding-bottom: 0px !important;">
<div class="span5">
<div class="control-group">
<label class="control-label" for="selectGroup">
Select Group:</label>
<div class="controls">
#Html.DropDownListFor(m => m.groupId, Model.groupList, "--Select Group--", new { #id = "selectGroup" })
</div>
</div>
</div>
<div class="span5">
<div class="control-group">
<label class="control-label" for="selectYear">
Select Year:</label>
<div class="controls">
#Html.DropDownListFor(m => m.yearId, Model.yearList, "--Select Year--", new { #id = "selectYear", onchange = "selectYear_indexChanged();" })
</div>
</div>
</div>
<div class="clearfix">
</div>
</div>
</div>
}
.....
}
You can't have nested forms. You can however have multiple forms per view.
See W3C for more info.