Adding a column which contains a hyperlink for every row in KendoUI grid control in ASP.NET MVC - asp.net-mvc-4

Here is my View that contains the KendoUI Grid Control:
I want to add a new column that contains a hyperlink before the Date of creation column .
#using Kendo.Mvc.UI
#model IEnumerable<ExamplekendoDropdown.Models.FacilityGroup>
#{
ViewBag.Title = "Grid";
}
<table width="700">
<tr>
<td align="center">
<table width="1000">
<tr>
<td align="left">
#using (Html.BeginForm("Grid", "Grid", FormMethod.Get))
{
<table>
<tr>
<td>
<span>Facility Group Name</span>
</td>
<td>
#(Html.Kendo().AutoComplete()
.Name("FacilityGroupName")
.Value("")
.Enable(true)
)
#Html.Hidden("FacilityGroupName")
</td>
</tr>
<tr>
<td>
<input id="Submit1" type="submit" value="Search" />
</td>
</tr>
</table>
}
</td>
</tr>
<tr>
<td align="center" >
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.FacilityGroupId);
//columns.Bound(#Html.ActionLink("Create Facility", "Facility"));
columns.Bound(p =>p.FaclityGroupName);
columns.Bound(p => p.status).Width(80);
columns.Bound(p => p.CreationDate);
columns.Command(command => { command.Edit(); });
})
//.ToolBar(toolbar =>toolbar.Create())
//.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("EditUserPopupTemplate")
.Window(w => w.Title("Facility").Name("editWindow").Width(300).Height(300)))
.Pageable()
.Sortable()
.Scrollable()
.DataSource(datasource => datasource
.Server()
.Model(model => model.Id(p => p.FacilityGroupId ))
.Read("Grid", "Grid")
.Update("Update", "Grid")
//.Create("Create","Grid")
//.Destroy("Destroy","Grid")
)
)
<script type="text/javascript">
$(document).ready(function () {
$("form.k-edit-form").kendoValidator();
});
</script>
</td>
</tr>
</table>
</td>
</tr>
</table>
Now i need to add another column before the "Date Of Creation" Column that contains a hyperlink.
Please share your inputs
Thanks

But why not this if you are using ajax
Ajax().ClientTemplate("#=FileName#");
if server()
columns.Bound(p => p.ProductID).Template(#<text>
#Html.ActionLink("Show Product Details", "ProductDetails", new { id = #item.ProductID } )>
</text>);
This example

columns.Template(#<text></text>).ClientTemplate(
#Html.ActionLink("Send Reset Email", "Login", new { loginButton = "reset",activate=true,fromAdmin=true,rowField="#=rowField#" }).ToHtmlString()
);
This worked for me.

You can use Template and ClientTemplate, to get a column with a hyperlink.
columns.Bound(p => p.CreationDate)
.Template(#<text>#item.CreationDate</text>)
.ClientTemplate("<a href=''>#CreationDate<a/>").Title("Link");
columns.Bound(p => p.CreationDate);

You only need to use the Template method for Server Binding. (ClientTemplate is for Ajax binding). You do not need to bind it to specific property unless you want to associate the column header to filter/sort/group by that property.
columns.Template(#<text>#Html.ActionLink("Create Facility", "Facility")</text>)

columns.Template(#<text></text>)
.ClientTemplate("<a href='" + Url.Action("Index", "Home") + "'>Create Facility</a>")
.HtmlAttributes(new { style = "text-align: left;" })
.Width(60);
This worked for me

If your grid has Server Binding use this:
columns.Bound(x => x.ProjectCode)
.Template(items => Html.ActionLink(items.ProjectCode, "Manage", "Project", new {projectId = items.ProjectId}, null));

Related

Cant write data in database using codeigniter

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{
}

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)

how to disable the dropdown based on another dropdown selected value in ASP.NET MVC

<tr>
<td class="einput">Admission Type :</td>
<td class="einput">
#Html.DropDownListFor(model => model.Adm_Type_LSeq, (SelectList)ViewBag.lstAdmType, String.Empty, new { #class = "drpclass" })
</td>
<td class="einput">Hostel Name :</td>
<td class="einput">
#Html.DropDownListFor(model => model.Hostel_Seq, (SelectList)ViewBag.lstHostel, String.Empty, new { #class = "drpclass" })
</td>
</tr>.
this is my code in html5 ...in this admission type have two values "hosteller" and "dayscholar" when i select admission type as dayscholar, hostel name dropdown should be disable then i select admission type as a hosteller hostel name dropdown should be enable.
this only my requirement ..please help me some one..thanks in advance.
Try this :
Jquery
$(document).ready(function () {
if ($("#Select1").val() == "dayscholar")
{
$("#Select2").attr('disabled','disabled');
}
else
{
$("#Select2").removeAttr('disabled');
}
$("#Select1").change(function () {
if ($(this).val() == "dayscholar")
{
$("#Select2").attr('disabled','disabled');
}
else
{
$("#Select2").removeAttr('disabled');
}
});
});
cshtml code :
<tr>
<td class="einput">Admission Type :
</td>
<td class="einput">
#Html.DropDownListFor(model => model.Adm_Type_LSeq, (SelectList)ViewBag.lstAdmType, String.Empty, new { #class = "drpclass" ,#id="Select1" })
</td>
<td class="einput">Hostel Name :
</td>
<td class="einput">
#Html.DropDownListFor(model => model.Hostel_Seq, (SelectList)ViewBag.lstHostel, String.Empty, new { #class = "drpclass",#id="Select2" })
</td>
</tr>
Demo : http://jsfiddle.net/Vx7H8/

Cannot pass SelectedValue and Text to Controller for a KendoUIDropDownListFor widget

This works fine if I don't use any KendoUI functionality and am able to pass it easily using a regular Html.DropDownListfor helper (seen as comments in the code). The Description and the StatusID both do not come through.
How can I pass these values to the controller after selecting them in the dropdown list and then clicking enter with the KendoUI extension?
If I uncomment the Value and Text properties, I get "Object not set to an instance of an Object".
#using (Html.BeginForm("AddSingleStatus", "Status", new AjaxOptions { HttpMethod = "POST", }))
{
#Html.ValidationSummary(true)
<table>
<tr>
<td>
<div class="display-label">
#Html.LabelFor(model => Model.Description);
</div>
<div class="display-label" style="display: none;">
#Html.HiddenFor(model => Model.Description)
</div>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(model => Model.StatusID)
.Name("statusDropDownList")
.DataTextField("Description")
.DataValueField("StatusID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("ReadDDL", "Status");
})
.ServerFiltering(false);
})
.OptionLabel("Select a status")
.SelectedIndex(0)
.Events(e => e
.Change("dropdownlist_change")
)
)
#* #Html.DropDownListFor(model => Model.StatusID, new SelectList((YeagerTechModel.Status[])ViewData["statuses"], "StatusID", "Description"));*#
#*#Html.ValidationMessageFor(model => Model.StatusID)*#
</div>
</td>
</tr>
<tr>
<td>
<input type="submit" id="ddlSubmit" value='#Resources.Add' />
</td>
</tr>
</table>
}
<script type="text/javascript">
function dropdownlist_change()
{
var dropdownlist = $("#statusDropDownList").data("kendoDropDownList");
dropdownlist.bind("change", function (e)
{
var value = dropdownlist.value();
});
}
</script>

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.