Kendo grid dropdown issue - kendo-ui

I have a view with tabs and each tab has a kendo grid with inline edit and have dropdown inside the grid. Problem which i am facing is when i update the value of the drop down is not showing the updated value but when i refresh the page the updated value is showing. But if i refresh the problem here is if i update the value is the sceond tab it i do refresh it will go to second tab. Is there any way I can acheive this without refesh.
#model BHI.TESQ.Entities.Interfaces.Models.ILocationAdminModel
#if (TempData["Result"] == "Data Saved Successfully")
{
<script>
alert('Location Data Saved Successfully');
</script>
}
#using (Html.BeginForm("SaveLocationAdmin", "Administration", FormMethod.Post))
{
<div style="margin-top: 45px;height:400px">
<h5 class="page-header k-block k-primary" style="overflow: hidden; margin-left: 5px; max-width: 1133px;">#ViewBag.Title</h5>
<table style="width: 100%; margin-top: 0px">
<tr style="margin-top: 0px;">
<td>
#*<table style="width: 100%">
<tr>
<td>*#
#(Html.Kendo().Splitter()
.Name("vertical")
.HtmlAttributes(new { style = "min-height:400px" })
.Orientation(SplitterOrientation.Horizontal)
.Panes(verticalPanes =>
{
verticalPanes.Add()
.Size("150px")
.HtmlAttributes(new { style = "min-height:400px" })
.Scrollable(false)
.Resizable(false)
.Content(Html.Action("AdminLinks").ToString());
verticalPanes.Add()
.HtmlAttributes(new { id = "top-pane" })
.Scrollable(false)
.Collapsible(false)
.Content(
Html.Kendo().Splitter()
.Name("horizontal")
.HtmlAttributes(new { style = "min-height:400px" })
.Panes(horizontalPanes =>
{
horizontalPanes.Add()
.HtmlAttributes(new { id = "left-pane" })
.Size("300px")
.Collapsible(true)
.Resizable(false)
.Content(#<div class="pane-content">
<h6 class="header k-block">Create New Location</h6>
<table>
<tr>
<td class="td-style">Location Name<span class="asterisk_input"></span></td>
<td>
<input id="txtLocName" name="txtLocName" type="text" class="textbox" required />
</td>
</tr>
<tr>
<td class="td-style">Country<span class="asterisk_input"></span></td>
<td>
#(Html.Kendo().DropDownList()
.Name("ddCountry")
.HtmlAttributes(new { required = "required" })
//.BindTo(new List<string>() {
// "United States",
// "United Kingdom (UK)",
// })
.BindTo(#Model.Country)
.OptionLabel("--Select Country--")
.DataTextField("CountryName")
.DataValueField("CountryId")
.Events(e => e.Change("OnCountryChange"))
)
<input type="hidden" id="hddCountry" name="hddCountry" value="" />
</td>
</tr>
<tr>
<td class="td-style">State</td>
<td>
#(Html.Kendo().DropDownList()
.Name("ddState")
.OptionLabel("--Select State--")
.DataTextField("StateName")
.DataValueField("StateId")
.Events(e => e.Change("OnStateChange"))
//.BindTo(new List<string>() {
// "Texas",
// })
.DataSource(source =>
{
source.Read(read => { read.Action("GetStateList", "Administration").Data("filterState"); }).ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("ddCountry")
)
<script>
function filterState() {
return {
countryId: $("#ddCountry").val()
};
}
</script>
<input type="hidden" id="hddState" name="hddState" value="" />
</td>
</tr>
<tr>
<td class="td-style">Location Status<span class="asterisk_input"></span></td>
<td>
#*#(Html.Kendo().DropDownList()
.Name("ddLocStatus")
.BindTo(new List<string>() {
"Active",
"In-Active",
})
)*#
<input id="chkBoxStatus" type="checkbox" name="chkBoxStatus" value="true" />
</td>
</tr>
<tr>
<td align="right">
#(Html.Kendo().Button()
.Name("btnInsert")
.Events(ev => ev.Click("onClick"))
.HtmlAttributes(new { type = "submit", #class = "btn btn-primary button" })
.Content("Save"))
</td>
<td>
#(Html.Kendo().Button()
.Name("btnCancel")
.HtmlAttributes(new { type = "button", #class = "btn btn-primary button" })
.Content("Cancel"))
</td>
</tr>
</table>
</div>
);
horizontalPanes.Add()
.HtmlAttributes(new { id = "center-pane" })
.Scrollable(false)
.Content(#<div>
#(Html.Kendo().Grid(Model.Locations)
.Name("Grid")
.HtmlAttributes(new { style = "min-height:400px" })
.Columns(columns =>
{
columns.Command(command => { command.Edit().HtmlAttributes(new { type = "button", #class = "btn btn-primary button" }); }).Width(100);
columns.Bound(p => p.LocationId).Width(140).Hidden(true);
columns.Bound(p => p.LocationName).Width(140);
columns.Bound(p => p.CountryId).EditorTemplateName("CountryNames").Title("CountryName").ClientTemplate("#:CountryName#").Width(150);
columns.Bound(p => p.StateId).EditorTemplateName("StateNames").Title("StateName").ClientTemplate("#:StateName#").Width(150);
columns.Bound(p => p.IsActive).Width(100);
})
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Pageable()
.Navigatable()
.Sortable()
.Scrollable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.ServerOperation(false)
.Events(events => { events.Error("error_handler"); events.RequestEnd("onRequestEnd"); })
.Model(model => { model.Id(p => p.LocationId); model.Field(p => p.LocationId).Editable(false); })
.Update(update => update.Action("Update_Location", "Administration"))
)
)
</div>
);
}).ToHtmlString()
);
})
)
</td>
</tr>
</table>
#*</td>
</tr>
</table>
*#
</div>
}
<style scoped>
#vertical {
width: 95%;
}
.pane-content {
width: 300px;
}
div.k-grid-content {
min-height: 300px;
}
</style>
<script type="text/javascript">
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
var grid = $("#Grid").data("kendoGrid");
grid.cancelChanges();
}
}
$(document).ready(function () {
$('#btnCancel').click(function () {
$(':input').not(':button, :submit, :reset, :hidden').val('')
$('input:checkbox').removeAttr('checked')
var dropdownlist = $("#ddCountry").data("kendoDropDownList");
dropdownlist.select(0);
var dropdownlist = $("#ddState").data("kendoDropDownList");
dropdownlist.select(0);
});
});
function onClick(e) {
var locationName = $("#txtLocName").val();
if (locationName != "") {
var selectedText = $("#ddCountry").data("kendoDropDownList").text();
if (selectedText == "--Select Country--") {
alert('Please select country');
}
}
}
function OnCountryChange(e) {
var selectedText = $("#ddCountry").data("kendoDropDownList").text()
$("#hddCountry").val(selectedText);
}
function OnStateChange(e) {
var selectedText = $("#ddState").data("kendoDropDownList").text()
$("#hddState").val(selectedText);
}
function onRequestEnd(e) {
if (e.type == "create" || e.type == "update") {
if (e.response == null || e.response.Errors == null) {
alert("Location Data Updated Successfully");
}
}
}
</script>

Ok. So taking your code sample and assuming a couple of things:
Your code:
public ActionResult Update_Parameter([DataSourceRequest] DataSourceRequest request, Parameter UpdatedParameter)
{
try
{
mTestAdminLogic.SaveModel((ITestAdminModel)model, ViewBag.ApplicationId, Operation.UpdateParameter);
}
catch (Exception ex)
{
ModelState.AddModelError("ParameterUpdateError", ex.Message);
}
return RedirectToAction("TestAdmin");
}
and these are my changes:
public JsonResult Update_Parameter([DataSourceRequest] DataSourceRequest request, Parameter UpdatedParameter)
{
var returnModel = {your return model here};
try
{
returnModel = mTestAdminLogic.SaveModel((ITestAdminModel)model, ViewBag.ApplicationId, Operation.UpdateParameter);
}
catch (Exception ex)
{
ModelState.AddModelError("ParameterUpdateError", ex.Message);
}
return Json(new[] { returnModel }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.DenyGet);
}
So let me explain.
If this action is only being used to update the Grid then change it to a JsonResult as the result of the grid update will be expecting JSON back.
I am assuming you have left our the declaration of your Data Layer logic and have cut it down to this single line:
mTestAdminLogic.SaveModel((ITestAdminModel)model, ViewBag.ApplicationId, Operation.UpdateParameter);
now if this model is different to the one expected by the grid the resulting action of this line should return back the appropriate model that the grid is expecting. As you have not declared that in your grid I am assuming it is some kind of LocationBasedModel.
Now once this update has completed then you should be returning back the appropriate model and adding the following Using statement using Kendo.Mvc.Extensions; this will give you access to the .ToDataSourceResult() extension method which will then allow you to transform this single model back to the grid and let the grid update its view of the data. Including the request and modelstate will also provide any errors and apply any existing filtering etc. back to the grid.
This would resolve the issue with the page "refreshing" itself everytime this action is called.
Any issues let me know and I will update my answer to reflect any changes you need.

Related

How can I refresh my partial view on my parent index after a modal update to add new information?

I am certain this question has been asked before, I don't think there is anything unique about my situation but let me explain. I have my Index View (Parent), on that Index View there is a partial View Dataset Contacts "links" (child), I have an Add Contact button, which pops a Modal and allows me to submit the form data to add to the database, when I return I want to only refresh the partial view of links. Note: the Controller Action Dataset_Contacts below needs to fire in order to refresh the partial view (child). It might go without saying, but I don't see this happening with my current code. Any assistance will be appreciated.
on my Index View index.cshtml I have the following code to render my partial View
<div class="section_container2">
#{ Html.RenderAction("Dataset_Contacts", "Home"); }
</div>
Here is the controller:
[ChildActionOnly]
public ActionResult Dataset_Contacts()
{
// Retrieve contacts in the Dataset (Contact)
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
var returned = new Dataset_Contact_View();
var dataset = new Dataset();
var contacts = new List<Contact>();
var contact_types = new List<Contact_Type>();
using (var client = new HttpClient())
{
dataset = JsonConvert.DeserializeObject<Dataset>(datasetResponse);
contact_types = JsonConvert.DeserializeObject<List<Contact_Type>>(ContactTypeResponse);
// Set up the UI
var ds_contact = new List<ContactView>();
foreach (Contact c in dataset.Contact)
{
foreach (Contact_Type t in contact_types)
{
if (c.Contact_Type_ID == t.Contact_Type_ID)
{
var cv = new ContactView();
cv.contact_id = c.Contact_ID;
cv.contact_type = t.Description;
returned.Dataset_Contacts.Add(cv);
}
}
}
}
return PartialView(returned);
}
Here is my Partial View Dataset_Contacts.cshtml
#model ResearchDataInventoryWeb.Models.Dataset_Contact_View
<table>
#{
var count = 1;
foreach (var ct in Model.Dataset_Contacts)
{
if (count == 1)
{
#Html.Raw("<tr>")
#Html.Raw("<td>")
<span class="link" style="margin-left:10px;">#ct.contact_type</span>
#Html.Raw("</td>")
count++;
}
else if (count == 2)
{
#Html.Raw("<td>")
<span class="link" style="margin-left:300px;">#ct.contact_type</span>
#Html.Raw("</td>")
#Html.Raw("</tr>")
count = 1;
}
}
}
</table>
Also on my Index.cshtml is my Add Contact button, which pops a modal
<div style="float:right;">
<span class="link" style="padding-right:5px;">Add</span>
</div>
jquery for the Modal:
var AddContact = function () {
var url = "../Home/AddContact"
$("#myModalBody").load(url, function () {
$("#myModal").modal("show");
})
};
Controller action for AddContact
public ActionResult AddContact()
{
return PartialView();
}
Modal for AddContact.cshtml
#model ResearchDataInventoryWeb.Models.Contact
<form id="contactForm1">
<div class="section_header2">Contact</div>
<div style="padding-top:5px;">
<table>
<tr>
<td>
<span class="display-label">UCID/Booth ID</span>
</td>
<td>
#Html.TextBoxFor(model => model.Booth_UCID, new { placeholder = "<Booth/UCID>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Type</span>
</td>
<td>
<select class="input-box" id="contact_type">
<option value="contact_type">Contact Type*</option>
<option value="dataset_admin">Dataset Admin</option>
<option value="dataset_Provider">Dataset Provider</option>
<option value="department">Department</option>
<option value="external_collaborator">External Collaborator</option>
<option value="principal_investigator">Principal Investigator</option>
<option value="research_center">Research Center</option>
<option value="vendor">Vendor</option>
</select>
</td>
</tr>
<tr>
<td>
<span class="display-label">Name</span>
</td>
<td>
#Html.TextBoxFor(model => model.First_Name, new { placeholder = "<First Name>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Last_Name, new { placeholder = "<Last Name>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Email</span>
</td>
<td>
#Html.TextBoxFor(model => model.Email, new { placeholder = "<Email 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Email_2, new { placeholder = "<Email 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Phone</span>
</td>
<td>
#Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "<Phone 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Phone_Number_2, new { placeholder = "<Phone 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Job Title</span>
</td>
<td>
#Html.TextBoxFor(model => model.Title_Role, new { placeholder = "<Job Title>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Organization</span>
</td>
<td>
<input class="input-box" type="text" placeholder="<Organization>" />
</td>
</tr>
</table>
<div style="padding-left:10px; margin-top:10px;">
<textarea rows="3" placeholder="Notes"></textarea>
</div>
</div>
<div class="centerButton" style="margin-top: 30px;">
<div style="margin-left:30px">
<submit id="btnSubmit" class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">SAVE</span></submit>
</div>
<div style="margin-left:30px">
<submit class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">REMOVE</span></submit>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var frm = $('#contactForm1').serialize()
$.ajax({
type: "POST",
url: "/Home/AddContact/",
data: frm,
success: function () {
$("#myModal").modal("hide");
}
})
})
})
</script>
and lastly Action for [HttpPost] AddContact(Contact data)
[HttpPost]
public ActionResult AddContact(Contact data)
{
// Update the Database here
return View();
}
My solution:
1. Change ActionResult to JsonResult
{
// Update the Database code
// END
return Json(new
{
dbUpdateResult = "success"
});
}
2. In Ajax:
//Ajax code
...
success: function (ajaxRespond) {
if(ajaxRespond.dbUpdateResult == "success"){
$("#myModal").modal("hide");
reloadTable()
}
}
Then you can use 1:
function reloadTable(){
$('#CONTAINER_ID').load('#Url.Action("Dataset_Contacts", "Home")');
}
Or 2:
function reloadTable(){
let myurl = '#Url.Action("Dataset_Contacts", "Home")';
$.ajax({
type: "GET",
url: myurl,
success: function (data, textStatus, jqXHR) {
$("#CONTAINER_ID").html(data);
},
error: function (requestObject, error, errorThrown) {
console.log(requestObject, error, errorThrown);
alert("Error: can not update table")
}
});
}
So you reload your partial view after successful dbupdate. Please tell me, if I'm wrong...

Validation and submit button don't function together in PartialView while using a composite model

Validation in my forms are defined in my Model.
If I don't include these two lines in my view:
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
The submit button works fine, but validation doesn't work. If I include these, validation starts working and the submit button doesn't work anymore.
I try to do the validation through my model.
My model:
public class TemplateDTO : DTOBase
{
public virtual int ID { get; set; }
[Required(ErrorMessage="فيلد ضروري")]
[RegularExpression("^[a-zA-z0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name { get; set; }
[RegularExpression("^[a-zA-zآ-ي0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name_Fr { get; set; }
public virtual IList<TemplateDetailsDTO> LstDetails { get; set; }
}
My composite model:
public class TemplateViewModel
{
public TemplateDTO Template { get; set; }
public List<TemplateFieldsDTO> TemplateFeilds { get; set; }
public int[] oSelectedFieldsDTO { get; set; }
public string Text { get; set; }
public bool NextLine { get; set; }
}
My Controller (ActionResult which calls the view and JsonResult which is the answer):
public ActionResult _NewTemplate()
{
if (myGlobalVariables.AllTemplateFieldsDTO == null)
{
TemplateFieldsClientService oTemplateFieldsClientService = new TemplateFieldsClientService();
myGlobalVariables.AllTemplateFieldsDTO = oTemplateFieldsClientService.GetAll();
}
TemplateDTO oTemplateDTO = new TemplateDTO();
oTemplateDTO.LstDetails = new List<TemplateDetailsDTO>();
TemplateViewModel x = new TemplateViewModel();
x.TemplateFeilds = myGlobalVariables.AllTemplateFieldsDTO;
x.Template = oTemplateDTO;
return PartialView(x);
}
[HttpPost]
public JsonResult _NewTemplate(TemplateViewModel oTemplateViewModel)
{
if (ModelState.IsValid)
{
if (oTemplateViewModel.Template != null)
{
if (oTemplateViewModel.Template.Name == null)
{
throw new System.ArgumentNullException("Parameter can not be null", "oTemplateDTO");
}
string strAttr = "";
if (oTemplateViewModel.NextLine)
strAttr = "\n";
List<TemplateDetailsDTO> LstTemDetails = new List<TemplateDetailsDTO>();
int Position = 0;
if (oTemplateViewModel.oSelectedFieldsDTO != null)
{
foreach (var i in oTemplateViewModel.oSelectedFieldsDTO)
{
TemplateDetailsDTO TempDetls = new TemplateDetailsDTO();
TempDetls.PositionNumber = ++Position;
TempDetls.Attributes = strAttr;
TemplateFieldsDTO OTemplateFieldsDTO = myGlobalVariables.AllTemplateFieldsDTO.Find(x => x.ID == i);
TempDetls.ObjFields = OTemplateFieldsDTO;
TempDetls.ObjTemplate = oTemplateViewModel.Template;
LstTemDetails.Add(TempDetls);
}
}
oTemplateViewModel.Template.LstDetails = LstTemDetails;
oTemplateClientService.AddNewTemplate(oTemplateViewModel.Template);
myGlobalVariables.AllTemplateDTO = oTemplateClientService.GetAllTemplate();
log.Info("Template added to Database.");
return Json(new { Result = "OK", Message = "عمليات ثبت با موفقيت انجام شد" }, JsonRequestBehavior.DenyGet);
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها ي ضروري را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
Code for my view:
#model IAC.SMS.MvcApp.Controllers.TemplateViewModel
<script type="text/javascript">
$(function () {
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
$('#btnAdd').click(function () {
$('#ListBoxSource').find('option:selected').appendTo('#oSelectedFieldsDTO');
})
$('#btnDelete').click(function () {
$('#oSelectedFieldsDTO').find('option:selected').appendTo('#ListBoxSource');
});
$('#btnUp').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var prevOption = $('#oSelectedFieldsDTO').find('option:selected').prev("option");
if ($(prevOption).text() != "") {
$(selectedOption).remove();
$(prevOption).before($(selectedOption));
}
});
$('#btnDown').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var nextOption = $('#oSelectedFieldsDTO').find('option:selected').next("option");
if ($(nextOption).text() != "") {
$(selectedOption).remove();
$(nextOption).after($(selectedOption));
}
});
});
function display() {
var dpt = document.getElementById("oSelectedFieldsDTO");
if (dpt.options[dpt.selectedIndex].text == "Text") {
document.getElementById("Text").disabled = false;
}
};
function SelectAllItems() {
$("#oSelectedFieldsDTO").each(function () {
$("#oSelectedFieldsDTO option").attr("selected", "selected");
});
};
//functions for ajax begin form
function Refresh() {
window.location.href = "#Url.Action("ListTemplate", "Template")" + "/";
}
function Success(data) {
if (data.Result == "OK") {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
Refresh();
}
else {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
}
function Fail() {
jSuccess(
'ارتباط برقرار نشد',
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
</script>
#using (Ajax.BeginForm("_NewTemplate", "Template", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "Success",
OnFailure = "Fail",
LoadingElementId = "Loading"
}, new { #id = "frmNewTemplate" }))
{
<table id="tblDetails" class="dataInput" style="width:500px;">
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مبدا
</label>
</td>
</tr>
<tr>
<td>
<label>
نام قالب
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name)
<label style="color:red; font-weight:bold;">*</label>
#Html.ValidationMessageFor(model => model.Template.Name)
</td>
<td></td>
<td rowspan="3">
#Html.ListBox("ListBoxSource", new SelectList(Model.TemplateFeilds, "ID", "Name", 1), new { size = 10 , style = "width:200px"})
</td>
</tr>
<tr>
<td>
<label>
توضيحات
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name_Fr)
</td>
</tr>
<tr>
<td>
<label>
پيام تکميلي
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Text , new { disabled="disabled"})
</td>
<td>
</td>
</tr>
<tr>
<td>
#Html.CH_CheckBoxFor(model=>model.NextLine, "خط بعد", false, false)
</td>
<td></td>
<td></td>
<td>
<button class="fixed button" id="btnAdd" type="button">اضافه<span class="left"></span> </button>
<button class="fixed button" id="btnDelete" type="button">حذف<span class="right"></span> </button>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مقصد
</label>
</td>
</tr>
<tr>
<td>
</td>
<td></td>
<td></td>
<td>
#Html.ListBoxFor(model => model.oSelectedFieldsDTO, new SelectList(Model.Template.LstDetails, "ID", "Name", 1), new { size = 10, style = "width:200px", onchange = "display()" })
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
</td>
<td>
<button class="fixed button" id="btnUp" type="button">بالا<span class="up"></span> </button>
<button class="fixed button" id="btnDown" type="button">پايين<span class="down"></span> </button>
</td>
</tr>
<tr>
<td>
#Html.HiddenFor(model=>model.Template.ID)
</td>
</tr>
</table>
<table>
<tr>
<td></td>
<td>
<div>
<button class="fixed button" type="submit" onmouseover="SelectAllItems()">ذخيره</button>
</div>
</td>
</tr>
</table>
}
Please tell me if I should include any more code.
My problem is that when I include the two lines code I mentioned above in my View to have validation, submit button in my PartialView won't function anymore, and the control doesn't go to the JsonResult function of my controller.
Thanks in Advance.
Update jquery.validate.min.js to version v1.12.0 - 4/1/2014 .
I hope you get the problem solved .

How to create page using Kendo Gird and Tabstrip

I want to select a row of grid and show detail row at tabstrip. The same image should attach.
Can anyone help me? I am using asp.net mvc 4 + Kendo Ui controls.
Image is here.
File CandidateController.cs
public ActionResult Index()
{
return View();
}
public ActionResult Can_Read([DataSourceRequest]DataSourceRequest request)
{
return Json(GetAllCan().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public ActionResult Can_ReadId([DataSourceRequest]DataSourceRequest request, Guid id)
{
return Json(GetCanById(id).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
In partial view: Candidate Info
#model RecruitmentOnlineMVC.Models.CandidateViewModel
<div class="candidate-detail" style="width: 827px!important">
<table>
<tr>
<th>Candidate Name</th>
<td>#(Html.TextBoxFor(model => model.CandidateName, new { #class = "k-input k-textbox" }))</td>
<th>ID</th>
<td>#Html.TextBoxFor(model => model.ID, new { #class = "k-input k-textbox" })</td>
</tr>
<tr>
<th>Email</th>
<td>#Html.TextBoxFor(model => model.Email, new { #class = "k-input k-textbox" })</td>
<th>Phone</th>
<td>#Html.TextBoxFor(model => model.Phone, new { #class = "k-input k-textbox" })</td>
</tr>
</table>
</div>
In View Index
#model RecruitmentOnlineMVC.Models.CandidateViewModel
#(Html.Kendo().Splitter()
.Name("splitter")
.Panes(panes =>
{
panes.Add()
.Content(#<div>
#(Html.Kendo().Grid<RecruitmentOnlineMVC.Models.CandidateViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.CandidateName);
columns.Bound(c => c.ID);
})
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Can_Read", "Candidate"))
)
.Pageable(pageable => pageable.ButtonCount(3))
.Filterable()
.Sortable()
.ColumnMenu()
.Events(e => e.Change("onSelected"))
)
</div>)
.Scrollable(true)
.Collapsible(true)
.Size("370px");
panes.Add()
.Content(#<div>
#(Html.Kendo().TabStrip()
.Name("tabstrip")
.Items(tabstrip =>
{
tabstrip.Add().Text("Candidate Detail")
.Selected(true)
.LoadContentFrom("/Candidate/CandidateInfo");
tabstrip.Add().Text("Work History")
.LoadContentFrom("/Candidate/WorkHistory");
})
)
</div>);
}))
Script
<script>
function onSelected() {
var can = this.select();
var propId = this.dataItem(can).ID;
\\In here, I want call action at Controller with propId and return detail on Tabstrip
Can anyone help me?
Thank so much !
I want to handled according to process like this :
Please guide me. Thank so much!
You need to make a seprate function in you controller with Json http post
and calls ajax request from the OnSelected() function..
following is the example
//Get Company List
[HttpPost]
public JsonResult GetCandidateDetails(string propId)
{
var Model= repository.GetCnadidatedetails(propId);
return Json(Model), JsonRequestBehavior.AllowGet);
}
<script>
function onSelected() {
var can = this.select();
var propId = this.dataItem(can).ID;
var dataItem = this.dataItem(e.item.index());
$.ajax({
url: '#Url.Action("GetCnadidatedetails", "Controller")',
//note: only string type is allowed as paramater to send to controller
data: { propId : this.propId },
dataType: "json",
type: "POST",
statusCode: {
404: function () {
showMessage("page not found.");
}
},
error: function () {
alert("error");
},
success: function (result) {
//add your result to tabstripe
$("#tabstrip").add(result.Id+result.Name);
}
});

Video file upload using ajax in mvc 3

How can I upload any video format in my project. Is it the same as uploading image?,coz I can upload image but I can't upload any video. Any tips? Thank you.
I update my question,as I said I can upload image using the code below,my problem is how can I upload video at the same time and with some other data.
#model BookingCMS.Models.Booking
#{
ViewBag.Title = "Index";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="#Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.fileupload.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/jquery.fileupload-ui.css")" rel="stylesheet" type="text/css" />
<br />
<br />
<fieldset>
<legend>
<h2>
Add Movie</h2>
</legend>
<br />
<table id="table-2">
<tbody>
<tr>
<td>
Movie Name
</td>
<td>#Html.TextBoxFor(model => model.MovieName, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Status
</td>
<td>#Html.CheckBoxFor(model => model.Status)
</td>
</tr>
<tr>
<td>
Showing Type
</td>
<td>#Html.DropDownList("ShowingTypes", ViewBag.ShowingType as IEnumerable<SelectListItem>, "Select Type")
</td>
</tr>
<tr>
<td>
Movie Codes
</td>
<td>
<input class="checkbox" type="checkbox" id="SC" />
<label class="label">
Standard Cinema</label>
#Html.TextBoxFor(model => model.StandardCinema, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="I2D" />
<label class="label">
IMAX2D</label>
#Html.TextBoxFor(model => model.Imax2D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="I3D" />
<label class="label">
IMAX 3D</label>
#Html.TextBoxFor(model => model.Imax3D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DC" />
<label class="label">
Directors Club</label>
#Html.TextBoxFor(model => model.DirectorsClub, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DT2D" />
<label class="label">
Digital Theatre 2D</label>
#Html.TextBoxFor(model => model.DigitalTheatre2D, new { #class = "textbox" })
<br />
<input class="checkbox" type="checkbox" id="DT3D" />
<label class="label">
Digital Theatre 3D</label>
#Html.TextBoxFor(model => model.DigitalTheatre3D, new { #class = "textbox" })
</td>
</tr>
<tr>
<td>
Cast
</td>
<td>#Html.TextBoxFor(model => model.Cast, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Rating
</td>
<td>#Html.TextBoxFor(model => model.Rating, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Genre
</td>
<td>#Html.TextBoxFor(model => model.Genre, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Cinexclusive
</td>
<td>#Html.CheckBoxFor(model => model.Cinexclusive)
</td>
</tr>
<tr>
<td>
Blurb
</td>
<td>#Html.TextAreaFor(model => model.Blurb, new { style = "width:500px; height: 150px" })
</td>
</tr>
<tr>
<td>
Synopsis
</td>
<td>#Html.TextAreaFor(model => model.Synopsis, new { style = "width:500px; height: 150px" })
</td>
</tr>
<tr>
<td>
Poster Homepage
</td>
<td style>
<form id="file_upload" action="/Movies/UploadFiles" method="POST" enctype="multipart/form-data">
<div class="fileupload-buttonbar">
#*<div class="progressbar fileupload-progressbar">
</div>*#
<div id="file_name">
</div>
<div id="file_type">
</div>
<div id="file_size">
</div>
<div id="show_image"></div>
<span class="fileinput-button"><a href="javascript:void(0)" class="upload-image">
Upload image</a>
<input type="file" name="files[]" multiple id="file" />
</span>
</div>
</form>
#*#Html.TextBox("PosterHomepage", (string)ViewBag.PosterHomepage, new { #class = "editor-field" })*#
</td>
</tr>
<tr>
<td>
Running Time
</td>
<td>#Html.TextBoxFor(model => model.RunningTime, new { #class = "editor-field" })
</td>
</tr>
<tr>
<td>
Trailer
</td>
<td>#Html.TextBoxFor(model => model.Trailer, new { #class = "editor-field" }) #*Here is my problem ..how can I upload video with some other data*#
</td>
</tr>
</tbody>
</table>
<br />
<div style="float: left">
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnCancel" value="Cancel" />
</div>
</fieldset>
<script type="text/javascript">
$(document).ready(function () {
$('.progressbar').progressbar({ value: 0 });
$('#file_upload').fileupload({
dataType: 'json',
url: '/Movies/UploadFiles',
progressall: function (e, data) {
$(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
},
done: function (e, data) {
$('#file_name').html(data.result.name);
$('#file_type').html(data.result.type);
$('#file_size').html(data.result.size);
$('#show_image').html('<img src="/home/image/' + data.result.name + '" />');
$('#file_name').css({ display: 'none' });
$('#file_type').css({ display: 'none' });
$('#file_size').css({ display: 'none' });
//visibility: hidden;
$(this).find('.progressbar').progressbar({ value: 100 });
}
});
});
$('#StandardCinema').hide();
$('#Imax2D').hide();
$('#Imax3D').hide();
$('#DirectorsClub').hide();
$('#DigitalTheatre2D').hide();
$('#DigitalTheatre3D').hide();
$('#SC').click(function () {
var check = $("#SC").is(':checked');//.attr('checked');
if (check == true) {
$('#StandardCinema').show();
$('#StandardCinema').focus();
}
else {
$('#StandardCinema').hide();
}
});
$('#I2D').click(function () {
var check = $("#I2D").is(':checked');
if (check == true) {
$('#Imax2D').show();
$('#Imax2D').focus();
}
else {
$('#Imax2D').hide();
}
});
$('#I3D').click(function () {
var check = $("#I3D").is(':checked');
if (check == true) {
$('#Imax3D').show();
$('#Imax3D').focus();
}
else {
$('#Imax3D').hide();
}
});
$('#DC').click(function () {
var check = $("#DC").is(':checked');
if (check == true) {
$('#DirectorsClub').show();
$('#DirectorsClub').focus();
}
else {
$('#DirectorsClub').hide();
}
});
$('#DT2D').click(function () {
var check = $("#DT2D").is(':checked');
if (check == true) {
$('#DigitalTheatre2D').show();
$('#DigitalTheatre2D').focus();
}
else {
$('#DigitalTheatre2D').hide();
}
});
$('#DT3D').click(function () {
var check = $("#DT3D").is(':checked');
if (check == true) {
$('#DigitalTheatre3D').show();
$('#DigitalTheatre3D').focus();
}
else {
$('#DigitalTheatre3D').hide();
}
});
$('#btnAdd').click(function () {
var e = document.getElementById("file_name");
var content = e.innerHTML;
//alert(content);
var _MovieName = $('#MovieName').val();
var _Active = $('#Status').val();
var _ShowingTypes = $('#ShowingTypes :selected').val();
var _ShowingTypesText = $('#ShowingTypes :selected').text();
var _Cast = $('#Cast').val();
var _Rating = $('#Rating').val();
var _Blurb = $('#Blurb').val();
var _Synopsis = $('#Synopsis').val();
var _RunningTime = $('#RunningTime').val();
var _Genre = $('#Genre').val();
var _Cinexclusive = $('#Cinexclusive');
var _Trailer = $('#Trailer').val();
var _PosterHomepage = content;
var _SC = $('#StandardCinema').val();
var _I2D = $('#Imax2D').val();
var _I3D = $('#Imax3D').val();
var _DC = $('#DirectorsClub').val();
var _DT2D = $('#DigitalTheatre2D').val();
var _DT3D = $('#DigitalTheatre3D').val();
var isSC = $("#SC").attr('checked') ? true : false;
var isI2D = $("#I2D").attr('checked') ? true : false;
var isI3D = $("#I3D").attr('checked') ? true : false;
var isDC = $("#DC").attr('checked') ? true : false;
var isDT2D = $("#DT2D").attr('checked') ? true : false;
var isDT3D = $("#DT3D").attr('checked') ? true : false;
var isActive = $('#Status').attr('checked') ? true : false;
var isCinex = $('#Cinexclusive').attr('checked') ? true : false;
if (_ShowingTypesText == "Select Type") {
alert("Showing Type is required.");
return false;
}
if (isSC == true & _SC == "") {
alert("Standard Cinema was selected! Movie code is required.");
$('#StandardCinema').focus();
return false;
}
if (isI2D == true & _I2D == "") {
alert("IMAX 2D was selected! Movie code is required.");
$('#Imax2D').focus();
return false;
}
if (isI3D == true & _I3D == "") {
alert("IMAX 3D was selected! Movie code is required.");
$('#Imax3D').focus();
return false;
}
if (isDC == true & _DC == "") {
alert("Director's Club was selected! Movie code is required.");
$('#DirectorsClub').focus();
return false;
}
if (isDT2D == true & _DT2D == "") {
alert("Digital Theatre 2D was selected! Movie code is required.");
$('#DigitalTheatre2D').focus();
return false;
}
if (isDT3D == true & _DT3D == "") {
alert("Digital Theatre 3D was selected! Movie code is required.");
$('#DigitalTheatre3D').focus();
return false;
}
var postData = {
moviename: _MovieName,
status: isActive,
showingtype: _ShowingTypes,
cast: _Cast,
rating: _Rating,
genre: _Genre,
cinexclusive: isCinex,
blurb: _Blurb,
synopsis: _Synopsis,
runningtime: _RunningTime,
trailer: _Trailer,
posterhompage: _PosterHomepage,
sc: _SC,
i2d: _I2D,
i3d: _I3D,
dc: _DC,
dt2d: _DT2D,
dt3d: _DT3D
};
$.ajax({
type: "POST",
url: "/Movies/CreateMovie",
dataType: "json",
traditional: true,
data: postData,
cache: false,
success: function (data) {
if (data.Result == "Success") {
jAlert(data.Message, "Notification", function () {
window.location = '/Home/Index';
});
}
else
jAlert(data.Message, "Notification"); //, function () {
//$('#code').focus();
//});
}
});
});
$("#btnCancel").click(function () {
window.location = "/Home/Index/";
});
</script>
Controller:
public FilePathResult Image()
{
string filename = Request.Url.AbsolutePath.Replace("/home/image", "");
string contentType = "";
var filePath = new FileInfo(Server.MapPath("~/Images") + filename);
var index = filename.LastIndexOf(".") + 1;
var extension = filename.Substring(index).ToUpperInvariant();
// Fix for IE not handling jpg image types
contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);
return File(filePath.FullName, contentType);
}
[HttpPost]
public ContentResult UploadFiles()
{
var r = new List<UploadHomePage>();
foreach (string file in Request.Files)
{
HttpPostedFileBase image = Request.Files[file] as HttpPostedFileBase;
if (image.ContentLength == 0)
continue;
string savedFileName = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(image.FileName));
image.SaveAs(savedFileName);
r.Add(new UploadHomePage()
{
Name = image.FileName,
Length = image.ContentLength,
Type = image.ContentType
});
}
ViewBag.PosterHomepage = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(r[0].Name));
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
[HttpPost]
public ActionResult CreateMovie(string moviename, bool status, int showingtype, string cast, string rating, string genre, bool cinexclusive, string blurb, string synopsis, string runningtime, string trailer, string posterhompage, string sc, string i2d, string i3d, string dc, string dt2d, string dt3d)
{
try
{
//Saving process
if (_WebResult.Result == 0)
{
return Json(new { Result = "Success", Message = _WebResult.Message.ToString() });
}
else
{
return Json(new { Result = "Error", Message = _WebResult.Message.ToString() });
}
}
catch (Exception)
{
return Json(new { Result = "Error", Message = "" + " failed to save." });
}
}

How to display text from a dropdown in MVC

I have a partial view that has to display records on the change of dropdown. The values are coming correctly but it is not being displayed in the tex boxes. Please help. THe code of my partial view looks like below
#using (Ajax.BeginForm("W2State", new AjaxOptions() { UpdateTargetId = "model", OnSuccess = "w2Updated", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" } ))
{
<fieldset id="currencyView" class="detailView">
<table>
<tr>
<td style="width: 100px;">Select Agency </td>
<td>
#*#Html.DropDownListFor(model => model.ReportingAgencies, new SelectList(Model.ReportingAgencies, "SelectedAgency.AgencyGuid", "SelectedAgency.Name"), new { id = "dropDownReportAgencies" })*#
#Html.DropDownListFor(model => model.ReportingAgencies, new SelectList(Model.ReportingAgencies, "SelectedAgency.AgencyGuid", "SelectedAgency.Name"), "--Select An Agency--", new { id = "dropDownReportAgencies" })
</td>
</tr>
<tr class="seperator"></tr>
<tr class="seperator"></tr>
<tr>
<td style="width: 100px;">#Html.LabelFor(model => model.W2StateLocal.Wages)</td>
<td> #Html.TextBoxFor(model => model.W2StateLocal.Wages)</td>
</tr>
<tr>
<td style="width: 100px;">#Html.LabelFor(model => model.W2StateLocal.Tax)</td>
<td>#Html.TextBoxFor(model => model.W2StateLocal.Tax)</td>
</tr>
</table>
<div id="rightButtonControls">
#if (Model.IsEditable)
{
<button id="btnSave" value="save">Save</button>
}
</div>
</fieldset>
}
#Html.HiddenFor(model => model.CompanyId, new { id = "CompanyId" })
#Html.HiddenFor(model => model.EmployeeId, new { id = "EmployeeId" })
#Html.HiddenFor(model => model.FilingYear, new { id = "FilingYear" })
<script type="text/javascript">
$(document).ready(function () {
$("#divLoader").css('display', 'none');
$('#dropDownReportAgencies').change(function () {
var selectedAgency = $('#dropDownReportAgencies option:selected').val();
var CompanyId = $('#CompanyId').val();
var EmployeeId = $('#EmployeeId').val();
var FilingYear = $('#FilingYear').val();
var url = '#Url.Action("W2State", "W2Generation")';
$.get(url, { agencyId: selectedAgency, companyId: CompanyId, employeeId: EmployeeId, filingYear: FilingYear },
function (data) {
});
});
});
You want to get text from dropdown in mvc through jQuery...
Your code is right but just missing something.. You used
var selectedAgency = $('#dropDownReportAgencies option:selected').val();
but instead of 'val' you have to use 'text'.. it means
var selectedAgency = $("#dropDownReportAgencies option:selected").text();
Try this....

Resources