Cant write data in database using codeigniter - sql

I have a controller, model and view file. I am trying to write data to database using the form on view file. I am trying to validate the post data using a mix of Codeigniter Validation library and some methods defined by. This validation is being done in Controller. Then I am trying to pass data array to the model. In the model I am trying to read the data array and build a query to insert data in database.
The problem is that no data is being written in the database.
I dont see any visible errors in the browser. I have been stuck on this for some time now. Any help is appreciated. Thanks in advance.
Controller
function add_customer() {
$this->load->model('Customer_Model');
$data['title'] = "Add New Customer";
$this->load->view('templates/header' , $data);
$this->load->view('dashboard/add_customer' , $data);
$this->load->view('templates/footer' , $data);
if($this->input->post())
{
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|customer_email_exists');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|customer_mobile_exists');
$this->form_validation->set_rules('address', 'Address', 'trim|required');
if ($this->form_validation->run()){
$customer_data = array(
'name' => $this->validation->name,
'email' => $this->validation->email,
'mobile' => $this->validation->mobile,
'address' => $this->validation->address
);
$this->Customer_Model->add_customer($customer_data);
}else{
}
}
}
public function customer_email_exists($email) {
$this->load->model('Customer_Model');
if(!$this->Customer_Model->email_exists($email)){
return true;
}else{
$this->form_validation->set_message('email_exists', 'Email already registered, try another one.');
return false;
}
}
public function customer_mobile_exists($mobile) {
$this->load->model('Customer_Model');
if(!$this->Customer_Model->mobile_exists($mobile)){
return true;
}else{
$this->form_validation->set_message('email_exists', 'Email already registered, try another one.');
return false;
}
}
}
Model
class Customer_Model extends CI_Model{
function add_customer($customer_data)
{
$data = array(
'id'=>'',
'name'=>$customer_data["name"],
'email'=>$customer_data["email"],
'mobile'=>$customer_data["mobile"],
'address'=>$customer_data["address"]
);
$this->db->insert('customer',$data);
$this->db->query($query);
}
public function email_exists($email) {
$this->db->where("email = '$email' AND email != ''");
$query = $this->db->get('customer');
if ($query->num_rows() > 0){
return true;
}else{
return false;
}
}
public function mobile_exists($mobile) {
$this->db->where('mobile',$mobile);
$query = $this->db->get('customer');
if ($query->num_rows() > 0){
return true;
}else{
return false;
}
}}
View
<section class="versir-section">
<div class="container">
<div class="row">
<div class="col-12">
<?php echo validation_errors(); ?>
<form method="post">
<table width="600" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="230">Customer Name</td>
<td width="329"><input type="text" name="name"/></td>
</tr>
<tr>
<td>Customer Email </td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>Customer Mobile </td>
<td><input type="text" name="mobile"/></td>
</tr>
<tr>
<td>Customer Address </td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="save" value="Save Data"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>

Hmm! I think in this code part you should get post data from input, not from validation
if ($this->form_validation->run()){
$customer_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'address' => $this->input->post('address'),
);
$this->Customer_Model->add_customer($customer_data);
}else{
}

Related

Cannot bind source type Umbraco.Web.Models.RenderModel to model type Repower.Cms.Umbraco.Models.Test

First of all I am new to Umbraco so if you see some basic mistakes don't judge me.
So I am creating currently a Login form which he goes to the database (check Username and Password) and reads the value which he returns and let's him Cannot bind source type Umbraco.Web.Models.RenderModel to model type Repower.Cms.Umbraco.Models.Test.
This Is my HTML:
#inherits Umbraco.Web.Mvc.UmbracoViewPage<Repower.Cms.Umbraco.Models.Test>
#{
Layout = "Master.cshtml";
}
<style type="text/css">
.btnStyle {
border: thin solid #000000;
line-height: normal;
width: 80px;
}
</style>
#using (Html.BeginForm("Test", "MembersProtectedPage", FormMethod.Post))
{
<div class="fontStyle">
<center>
<table style="margin-top: 100px;margin-left:150px">
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.User)
</td>
<td style="width:200px" align="right">
#Html.TextBoxFor(m => m.User)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.User)
</td>
</tr>
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.Password)
</td>
<td align="right">
#Html.PasswordFor(m => m.Password)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.Password)
</td>
</tr>
<tr style="height:30px">
<td colspan="2" align="center">
<input type="submit" value="Sign In" class="btnStyle" />
</td>
</tr>
</table>
</center>
</div>
}
This is my Model:
public class Test : RenderModel
{
public Test() : this(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { }
public Test(IPublishedContent content, CultureInfo culture) : base(content, culture) { }
public Test(IPublishedContent content) : base(content) { }
string connString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
SqlConnection conn;
SqlCommand sqlcomm;
public string User { get; set; }
public string Password { get; set; }
public bool IsUserExist(string emailid, string password)
{
bool flag = false;
conn = new SqlConnection(connString);
conn.Open();
sqlcomm = new SqlCommand();
sqlcomm.Connection = conn;
sqlcomm.CommandType = System.Data.CommandType.StoredProcedure;
sqlcomm.CommandText = "dbo.uspLogin";
sqlcomm.Parameters.AddWithValue("#pLoginName", User);
sqlcomm.Parameters.AddWithValue("#pPassword", Password);
SqlParameter retval = sqlcomm.Parameters.Add("#RESULT", SqlDbType.VarChar);
retval.Direction = ParameterDirection.ReturnValue;
sqlcomm.ExecuteNonQuery(); // MISSING
string retunvalue = (string)sqlcomm.Parameters["#RESULT"].Value;
switch (retunvalue)
{
case "0":
flag = true;
break;
case "1":
flag = false;
break;
case "2":
flag = false;
break;
default:
flag = false;
break;
}
return flag;
}
}
And this is my Controller:
public class TestController : Controller
{
public ViewResult Login()
{
return View();
}
[HttpPost, ValidateInput(false)]
public ActionResult Login(Test model)
{
if (ModelState.IsValid)
{
if (model.IsUserExist(model.User, model.Password))
{
ViewBag.UserName = model.User;
FormsAuthentication.RedirectFromLoginPage(model.User, false);
}
else
{
ModelState.AddModelError("", "Username or Password Incorrect.");
}
}
return View(model);
}
}
So I am inheriting a RenderModel because previously my error was "The model item passed into the dictionary is of type Repower.Cms.Umbraco.Models.Test', but this dictionary requires a model item of type 'Umbraco.Web.Models.RenderModel'."
So I changed it (searched a lot in the Internet) and now I get this error.
Is also the rest of the code correct? The way that I access the Database and everything? I am expecting a Return value from the Database (don't know if that is correct)
Could Someone please help me?
I need to get this done today.
Thanks in Advance
There's a few issues with your implementation.
Use the Umbraco MemberService
You're reinventing the wheel by building a new table which holds member information (such as username and password).
Umbraco has built in membership which can handle members of your site. You can view the GUI in Umbraco at /umbraco/#/member. Using this GUI, you can manually create and edit members.
You can also programmatically create end edit members in this section using this MemberService.
For example, register a member:
var MemberService = ApplicationContext.Current.Services.MemberService
var member = MemberService.CreateMemberWithIdentity(newEmail, newEmail, newName, "Member");
MemberService.Save(member);
MemberService.SavePassword(member, newPassword);
FormsAuthentication.SetAuthCookie(newEmail, true);
Login:
var memberService = ApplicationContext.Current.Services.MemberService;
if (memberService.Exists(email))
{
if (Membership.ValidateUser(email, password))
{
FormsAuthentication.SetAuthCookie(email, true);
}
}
You can read about what other methods are available here.
You're mixing up your MVC
Your Test model isn't purely a model, is also has some controller in it as it is handling database stuff too!
Ideally, your model should just contain the data which has been sent forward, and your TestController should handle using that data.
As for fixing your binding issue
You're currently setting your page view model to Repower.Cms.Umbraco.Models.Test, where as I think it should be left as is.
Stop this model from inheriting from RenderModel.
Instead, render a partial with your code.
For your page view:
#inherits Umbraco.Web.Mvc.UmbracoViewPage
#{
Layout = "Master.cshtml";
}
#Html.Partial("Login", new Repower.Cms.Umbraco.Models.Test())
Partial called Login.cshtml:
#model Repower.Cms.Umbraco.Models.Test
#using (Html.BeginUmbracoForm<TestController>("Login"))
{
<div class="fontStyle">
<center>
<table style="margin-top: 100px;margin-left:150px">
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.User)
</td>
<td style="width:200px" align="right">
#Html.TextBoxFor(m => m.User)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.User)
</td>
</tr>
<tr style="height:30px">
<td align="right">
#Html.LabelFor(m => m.Password)
</td>
<td align="right">
#Html.PasswordFor(m => m.Password)
</td>
<td style="width:250px;color:Red" align="left">
#Html.ValidationMessageFor(m => m.Password)
</td>
</tr>
<tr style="height:30px">
<td colspan="2" align="center">
<input type="submit" value="Sign In" class="btnStyle" />
</td>
</tr>
</table>
</center>
</div>
}
Finally, update your controller to inherit from SurfaceController.
I hope this helps
This isn't the complete solution but should help you get off on the right track.

Second Form Action, how to get value from Html.TextBoxFor

already looked at get value from Html.TextBoxFor and several other places.
I want to pass the UserName to a lost password screen. I added name="bjh" and id="bjh" as names that would not be used elsewhere, originally I used Username the value from my model (m.Username).
The normal login works, values get passed but my forgot password link #LangStrings.LostPassword doesn't get the username value from
#Html.TextBoxFor(m => m.Username, new { style = "width:100%" ,id="bjh",name="bjh"})
Login VIEW
#model HelpDesk.Models.LoginUserModel
#using (Html.BeginForm("Login", "User", new { ReturnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post))
{
<table class="grey" >
<tr><td colspan="2"><h2>#LangStrings.Login
#if (Settings.AllowUserRegistration) {
<span class="grey"><span style="font-weight:normal">#LangStrings.Or</span>
#LangStrings.Register</span>
}
</h2><div>#Html.ValidationSummary(false)</div></td></tr>
<tr>
<td><span style="font-size:14px">#LangStrings.Username #LangStrings.Or #LangStrings.Email</span></td>
<td><span style="font-size:14px">#Html.TextBoxFor(m => m.Username, new { style = "width:100%" ,id="bjh",name="bjh"})</span></td>
</tr>
<tr>
<td></td>
<td style="padding-top: 16px;">
<input id="Login" type="submit" value="#LangStrings.Login" style="font-weight:bold; font-size:16px " />
#if (Settings.EnableSaml) { <text><input type="submit" name="samlButton" class="graybutton" value="SAML Login" /></text> }
</td>
</tr>
<tr>
<td></td>
<td>#LangStrings.LostPassword
</td>
</tr>
</table>
}
Controller
[AllowAnonymous]
public ActionResult LostPassword(string bjh)
{
var a = bjh;
if (string.IsNullOrWhiteSpace(a))
{
a = "empty";
}
return View(new LostPasswordModel() { Email = a });
}
[AllowAnonymous]
[HttpPost]
public ActionResult LostPassword(LostPasswordModel model)
{
if (model.Email.IndexOf("#") <0)
{
//not email, so clear found value
}
if (ModelState.IsValid)
{
if (!model.ResetPsw(Url.AbsoluteAction("Login", "User", null)))
ModelState.AddModelError(String.Empty, LangStrings.Email_not_found);
else
ModelState.AddModelError(String.Empty, LangStrings.Success__An_email_has_been_sent__Check_your_inbox_after_a_while_);
}
return View(model);
}
Changing the href around slightly in the view solved the problem, used javascript and Jquery to get the value.
#LangStrings.LostPassword

How do I post this model in MVC 4 (null model)

My problem is quite common but I can't seem to figure out on my own why when I POST my model that it's null. My FormCollection seems to suggest it doesn't understand the whole model which it is POSTING. See code below:
My model - CaseForm.cs
namespace Models.CaseForm
{
public class CaseForm
{
public CaseForm()
{
this.Person = new Person();
this.Case = new Case();
this.Cases = new List<Case>();
}
public string strMessage;
public bool isValidModel;
public Person Person = new Person();
public Case Case = new Case();
public List<Case> Cases = new List<Case>();
}
}
My view = NewCase.cshtml
#model Models.CaseForm.CaseForm
#using (Html.BeginForm())
{
#Html.Raw(Model.strMessage)
<br />
#*#Html.HiddenFor(m => m.Case.CaseId)
#Html.HiddenFor(m => m.Case.CaseNotes)
#Html.HiddenFor(m => m.Case.CaseRef)
#Html.HiddenFor(m => m.Case.FirstAppointmentMade)
#Html.HiddenFor(m => m.Case.IsClosedRecord)
#Html.HiddenFor(m => m.Case.IsFirstContact)
#Html.HiddenFor(m => m.Case.PersonId)
#Html.HiddenFor(m => m.Case.ReasanForContact)
#Html.HiddenFor(m => m.Case.WasAdvisedByEmail)*#
<legend>
<fieldset>
<h4>New Case for #Html.Raw(Model.Person.Firstname + " " + Model.Person.Firstname)</h4>
</fieldset>
</legend>
<table>
<tr>
<td>#Html.LabelFor(m => m.Person.PersonRef)</td>
<td>#Html.DisplayFor(m => m.Person.PersonRef)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.Person.LesasPerson.ActionTakenPending, "Action Taken Pending")</td>
<td>#Html.DisplayFor(m => m.Person.LesasPerson.ActionTakenPending)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.Person.LesasPerson.DateArrivedInUk, "Date Arrived In UK")</td>
<td>#Html.DisplayFor(m => m.Person.LesasPerson.DateArrivedInUk)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.Person.LesasPerson.ImmigrationStatus, "Immigration Status")</td>
#{
string ImmigrationStatus = Model.Person.LesasPerson.ImmigrationStatus == null ? "No status set for this person" : Model.Person.LesasPerson.ImmigrationStatus;
}
<td>#Html.Raw(ImmigrationStatus)</td>
</tr>
</table>
<br />
<div id="divCase" style="border-style: solid; border-width: thin; padding: 5px;">
<table>
<tr>
<td><b>If Case ref is not known then leave blank for now.</b></td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Case.CaseRef, "Case Reference code")
</td>
<td>
#Html.TextBoxFor(m => m.Case.CaseRef)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Case.FirstAppointmentMade, "First Appointment Made")
</td>
<td>
#Html.TextBoxFor(m => m.Case.FirstAppointmentMade)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Case.IsFirstContact, "Is First Contact")
</td>
<td>
#Html.CheckBoxFor(m => m.Case.IsFirstContact)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Case.ReasanForContact, "Reason For Contact")
</td>
<td>
#{
List<SelectListItem> Reasons = new List<SelectListItem>();
Reasons.Add(new SelectListItem() { Text = "One Off Advice", Value = "One Off Advice", Selected = false });
Reasons.Add(new SelectListItem() { Text = "Housing", Value = "Housing", Selected = true });
Reasons.Add(new SelectListItem() { Text = "Immigration", Value = "Immigration", Selected = false });
Reasons.Add(new SelectListItem() { Text = "Social Advice", Value = "Social Advice", Selected = false });
Reasons.Add(new SelectListItem() { Text = "Legal", Value = "Legal", Selected = false });
Reasons = Reasons.OrderBy(r => r.Text).ToList();
}
#Html.DropDownListFor(m => m.Case.ReasanForContact, Reasons)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Case.WasAdvisedByEmail, "Was Advised By Email")
</td>
<td>
#Html.CheckBoxFor(m => m.Case.WasAdvisedByEmail)
</td>
</tr>
</table>
<hr />
<div id="divCaseNote" style="padding:10px;">
#for (int i = 0; i < Model.Case.CaseNotes.Count; i++)
{
int status = i + 1;
<table>
<tr>
<td>#Html.Label("This is note: " + status.ToString())</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.Case.CaseNotes[i].CaseStatus, "Write title or status for note")</td>
<td>#Html.TextBoxFor(m => m.Case.CaseNotes[i].CaseStatus)</td>
<td>#Html.ValidationMessageFor(m => m.Case.CaseNotes[i].CaseStatus)</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.Case.CaseNotes[i].CaseNote, "Case Note")</td>
<td>#Html.TextAreaFor(m => m.Case.CaseNotes[i].CaseNote)</td>
<td>#Html.ValidationMessageFor(m => m.Case.CaseNotes[i].CaseNote)</td>
#*#Html.HiddenFor(m => m.Case.CaseNotes[i].CaseDate)
#Html.HiddenFor(m => m.Case.CaseNotes[i].CaseId)
#Html.HiddenFor(m => m.Case.CaseNotes[i].CaseNote)
#Html.HiddenFor(m => m.Case.CaseNotes[i].CaseNoteId)
#Html.HiddenFor(m => m.Case.CaseNotes[i].CaseStatus)*#
</tr>
</table>
}
</div>
<input type="submit" value="Add Note For Case" name="btnSubmit" />
<input type="submit" value="Remove Note For Case" name="btnSubmit" />
</div>
<br />
<input type="submit" value="Save Case To Database" name="btnSubmit" />
<br />
<b>#Html.ActionLink("Go back to people grid", "PeopleDashboard")</b>
}
ActionResult NewCase (POST)
[HttpPost]
public ActionResult NewCase(string btnSubmit, FormCollection form, CaseForm Model)
{
RepositoryLesas RepositoryLesas = new RepositoryLesas();
switch (btnSubmit)
{
case "Add Note For Case":
#region AddClaimStatus
Model.Case.CaseNotes.Add(new CaseNotes());
// SET to false as Model is not ready for DB
Model.isValidModel = false;
// SET message for the user
Model.strMessage = "Type new note information in the fields below";
return View("~/Views/Case/NewCase.cshtml", Model);
#endregion
case "Remove Note For Case":
#region RemoveClaimStatus
// Can't remove IF only 1
Model.isValidModel = false;
if (Model.Case.CaseNotes.Count == 0 || Model.Case.CaseNotes.Count == 1)
{
Model.strMessage = "Must be at least one case note before saving case";
}
else
{
Model.Case.CaseNotes.RemoveAt(Model.Case.CaseNotes.Count - 1);
Model.strMessage = "One case note removed.";
}
return View("~/Views/Case/NewCase.cshtml", Model);
#endregion
//case "Save Case To Database":
//#region submit
//if (!Model.isValidModel)
//{
// RepositoryLesas.InsertClaim(Model);
// // Do one final check before going to success screen
// Model.strMessage = "Claim data inserted into the database.";
// Model.Person = RepositoryLesas.GetPerson(Model.Person.PersonID);
// // Use to persist data through redirect - Model data will be lost otherwise
// TempData["Model"] = Model;
// return RedirectToAction("Success", new { URL = SuccessClaimUrl });
//}
//else
//{
// Model.strMessage = "Claim data could not be inserted into the database. Missing key fields.";
// return View("~/Views/Claim/AddClaim.cshtml", Model);
//}
//#endregion
}
return View("~/Views/Case/NewCase.cshtml", Model);
}
My FormCollection
In my form collection, it only interprets the case object, it should show:
strMessage
isValidModel
Case obj
Cases collection
Person obj
Why is this model not posting correctly?
You need getter and setter on your properties. The DefaultModelBinder creates a new instance of CaseForm but can set the values of its properties that have been posted back because they dont have setters.
public class CaseForm
{
public string strMessage { get; set; }
public bool isValidModel { get; set; }
....
public List<Case> Cases { get; set; }
}
Note you do not need the parameter FormCollection form
Note also your are rendering hidden inputs for some properties
#Html.HiddenFor(m => m.Case.CaseRef)
and then creating a textbox for the same property
#Html.TextBoxFor(m => m.Case.CaseRef)
You need to remove the HiddenFor because it will only bind the first value on post back (the value in the hidden input) and ignore the second (the value in the textbox)

MVC 4 - Return error message from Controller - Show in View

I am doing a C# project using Razor in VS2010 (MVC 4).
I need to return an error message from Controller to View and show it to the user.
What I have tried:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
ModelState.AddModelError("error", "adfdghdghgdhgdhdgda");
ViewBag.error = TempData["error"];
return RedirectToAction("Form_edit", "Form");
}
VIEW:
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary("error")
#Html.ValidationMessage("error")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Please help me to achieve this.
The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
if(ModelState.IsValid())
{
--- operations
return Redirect("OtherAction", "SomeController");
}
// here you can use a little trick
//fill the model property that holds the information for the dropdown with the data
// you haven't provided the get method but it should look something like this
model.Countries = ... some data goes here;
model.dd_value = ... some other data;
model.dd_text = ... other data;
ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
return View(model);
}
and then in the view just use :
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary(true)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
This should work okay.
If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.
other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
TempData["error"] = "someErrorMessage";
return RedirectToAction("form_Post", "Form");
}
[HttpGet]
public ActionResult form_edit()
{
do stuff here ----
ViewData["error"] = TempData["error"];
return View();
}
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
<div>#ViewData["error"]</div>
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Thanks for all the replies.
I was able to solve this by doing the following:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
return RedirectToAction("Form_edit", "Form", model);
}
public ActionResult form_edit(FormModels model, string searchString,string id)
{
string test = model.selectedvalue;
var bal = new FormModels();
bal.Countries = bal.get_contentdetails(searchString);
bal.selectedvalue = id;
bal.dd_text = "content_name";
bal.dd_value = "content_id";
test = model.error_msg;
ViewBag.head = "Heading";
if (model.error_msg != null)
{
ModelState.AddModelError("error_msg", test);
}
model.error_msg = "";
return View(bal);
}
VIEW:
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#ViewBag.error
#Html.ValidationMessage("error_msg")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
}
If you want to do a redirect, you can either:
ViewBag.Error = "error message";
or
TempData["Error"] = "error message";
You can add this to your _Layout.cshtml:
#using MyProj.ViewModels;
...
#if (TempData["UserMessage"] != null)
{
var message = (MessageViewModel)TempData["UserMessage"];
<div class="alert #message.CssClassName" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>#message.Title</strong>
#message.Message
</div>
}
Then if you want to throw an error message in your controller:
TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger alert-dismissible", Title = "Error", Message = "This is an error message" };
MessageViewModel.cs:
public class MessageViewModel
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
Note: Using Bootstrap 4 classes.

how to checked checkbox using view model

i try to make a simple project, that check the list of checkbox. my database is like this... !
i want to check my checkbox when hotel have the facilities...
i have code like this...
my controller
public ActionResult Facility()
{
var model = db.Facilities
.Where (htl => htl.FacilityID == hotelFacility.FacilityID)
.Select(htl => new CheckFacilityVM
{
FacilityID = htl.FacilityID,
facilityName = htl.FacilityName,
facilityAvailable = htl.IsActive == true,
})
.ToList();
return View(model);
}
my constuctor class
public Facility ShowRoomFacility(int HotelID)
{
var x = (from d in db.Facilities
where d.FacilityID == HotelID
select d).FirstOrDefault();
return x;
}
my view
#model List<XNet.WebUI.Hotel.ViewModel.CheckFacilityVM>
#{
ViewBag.Title = "Facility";
}
<h2>Facility</h2>
#using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th> is available</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(x => x[i].FacilityID)
#Html.HiddenFor(x => x[i].FacilityID)
</td>
<td>
#Html.DisplayFor(x => x[i].facilityName)
#Html.HiddenFor(x => x[i].facilityName)
</td>
<td>
#Html.CheckBoxFor(x => x[i].facilityAvailable)
</td>
</tr>
}
</tbody>
</table>
}
<br />
<input style="width:100px;" type="button" title="Save" value="Save" onclick="location.href='#Url.Action("Index","Hotel")'" />
<input style="width:100px;" type="button" title="Reset" value="Reset" onclick="location.href='#Url.Action("Facility","Hotel")'" />
<input style="width:100px;" type="button" title="Cancel" value="Cancel" onclick="location.href='#Url.Action("Room","Hotel")'" />
how can i make checkbox is checked ??
help me please
You want to store the true/false in your database as a bit. 0 is false and 1 is true.
Then when you have a boolean property in your view model, populated by your database
public bool FacilityXAvailable { get; set; }
On your view you can then just do this
#Html.DisplayFor(model=>model.FacilityXAvailable)
That will display a checkbox checked on unchecked depending on Db value.