MVC2 ajax partial view does not register jquery scripts - asp.net-mvc-2

I have my page where i have ajax call to display form.
My code works when the register the code for form but not from postback (validation error in controller).
any idea how to fix this?
My container page has:
Scripts:
<%= Html.JQuery() %>
<script src="../../../../Scripts/jquery.ui.core.js" type="text/javascript"></script>
<script src="../../../../Scripts/jquery.ui.datepicker.min.js" type="text/javascript"></script>
<script src="../../../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../../../Scripts/MicrosoftMvcAjax.js" type="text/javascript">/script>
<script src="../../../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script type="text/javascript">
function registerStuff() {
//this gets triggered when onsuccess is called
$("#date").datepicker({ dateFormat: 'dd/mm/yy' });
$("#sla").datepicker();
}
</script>
Content:
<%= Ajax.AjaxButton("New action", "CreateWorkFlowAction", new {
controller = "CaseWorkFlow" }, new AjaxOptions() { UpdateTargetId =
"divTableContainer", HttpMethod = "Get", OnSuccess =
"registerStuff"})%>
<div id="divTableContainer">
response will appear here
</div>
my form looks like
<script type="text/javascript">
function RegisterJs() {
$("#date").datepicker({ dateFormat: 'dd/mm/yy' });
$("#sla").datepicker({ dateFormat: 'dd/mm/yy' });
}
</script>
<% Html.EnableClientValidation(); %>
<% using (Ajax.BeginForm("CreateWorkFlowAction", new AjaxOptions() { UpdateTargetId = "divTableContainer", HttpMethod = "Post" }))
{%>
<%= Html.ValidationSummary() %>
<fieldset>
<div>
<label for="title">
Title</label>
<%= Html.TextBoxFor(x=>x.Title) %>
</div>
<div>
<label for="SLA">
SLA(Due Date)</label>
<%= Html.TextBoxFor(x => x.SelectSlaDate, new { id = "sla", #Value = string.Empty} )%>
</div>
<div>
<label for="date">
Date</label>
<%= Html.TextBoxFor(x => x.SelectDate, new { id = "date", #Value = string.Empty})%>
</div>
<div>
<button type="submit">Save action</button>
</div>
</fieldset>
<% } %>
the problem is

i have found the solution to my question.
I have to reregister my javascript inside of a partial view.
this means that i had to update add register scripts into the parent page to which i will insert partial view.
and therfore if my view page contains partial view i had to move
function registerStuff() {
//this gets triggered when onsuccess is called
$("#date").datepicker({ dateFormat: 'dd/mm/yy' });
$("#sla").datepicker();
}
to the index page.
After on success call this function "registerStuff" from my oncomplete,
and after then everything is working like charm
hope this helps to you too

Related

Is it possible to call another parital to the harpe js parameter?

I'm harp js user and im curious if its possible to call another parital to the harp js parameter?
I would like to proceed with modularization to reuse the code.
It is difficult to use the parital function of harp to insert data into a module of a particular module into another module.
This is my sources:
//component/button.ejs
<button><%= lable %></button>
//component/tab.ejs
<div class="tab">
<div class="tab__nav">
<% for(var i in locals.payload){ %>
<div class="tab__nav-item"><%- locals.payload[i].name %></div>
<% }; %>
</div>
<div class="tab__content">
<% for(var i in locals.payload){ %>
<div class="tab__content-item">
<div class="container">
<%- locals.payload[i].content %>
</div>
</div>
<% }; %>
</div>
</div>
//page.ejs
<%- partial("component/tab",{
payload: [
{
name:'tab1',
content:`
<div><%= partial("component/button.ejs",{label:"btn"})%></div>
`
},
{
name:'tab2',
content: `
<div>111111</div>
`
}
]}) %>

Error submitting form data using knockout and mvc

#model NewDemoApp.Models.DemoViewModel
#{
ViewBag.Title = "Home Page";
}
#*<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>*#
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="#Url.Content("~/Scripts/knockout-3.3.0.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
var viewModel;
var compViewModel, userViewModel;
$(document).ready(function () {
$(".wizard-step:visible").hide();
$(".wizard-step:first").show(); // show first step
$("#back-step").hide();
var result = #Html.Raw(Json.Encode(Model));
var viewModel = new DemoViewModel(result.userViewModel);
//viewModel.userViewModel.FirstName = result.userViewModel.FirstName;
//viewModel.userViewModel.LastName = result.userViewModel.LastName;
//viewModel.userViewModel.State = result.userViewModel.State;
//viewModel.userViewModel.City = result.userViewModel.City;
ko.applyBindings(viewModel);
});
var userVM = function(){
FirstName = ko.observable(),
LastName = ko.observable(),
State = ko.observable(),
City = ko.observable()
};
function DemoViewModel(data) {
var self = this;
self.userViewModel = function UserViewModel(data) {
userVM.FirstName = data.FirstName;
userVM.LastName = data.LastName;
userVM.State = data.State;
userVM.City = data.City;
}
self.Next = function () {
var $step = $(".wizard-step:visible"); // get current step
var form = $("#myFrm");
var validator = $("#myFrm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
if ($step.next().hasClass("confirm")) { // is it confirmation?
$step.hide().prev(); // hide the current step
$step.next().show(); // show the next step
$("#back-step").show();
$("#next-step").hide();
//$("#myFrm").submit();
// show confirmation asynchronously
//$.post("/wizard/confirm", $("#myFrm").serialize(), function (r) {
// // inject response in confirmation step
// $(".wizard-step.confirm").html(r);
//});
}
else {
if ($step.next().hasClass("wizard-step")) { // is there any next step?
$step.hide().next().fadeIn(); // show it and hide current step
$("#back-step").show(); // recall to show backStep button
$("#next-step").show();
}
}
}
self.Back = function () {
var $step = $(".wizard-step:visible"); // get current step
if ($step.prev().hasClass("wizard-step")) { // is there any previous step?
$step.hide().prev().fadeIn(); // show it and hide current step
// disable backstep button?
if (!$step.prev().prev().hasClass("wizard-step")) {
$("#back-step").hide();
$("#next-step").show();
}
else {
$("#back-step").show();
$("#next-step").show();
}
}
}
self.SubmitForm = function (formElement) {
$.ajax({
url: '#Url.Content("~/Complaint/Save")',
type: "POST",
data: ko.toJS(self),
done: function (result) {
var newDiv = $(document.createElement("div"));
newDiv.html(result);
},
fail: function (err) {
alert(err);
},
always: function (data) {
alert(data);
}
});
}
self.loadData = function () {
$.get({
url: '#Url.Content("~/Complaint/ViewComplaint")',
done: function (data) {
debugger;
alert(data);
self.compViewModel(data);
self.userViewModel(data);
},
fail: function (err) {
debugger;
alert(err);
},
always: function (data) {
debugger;
alert(data);
}
});
}
}
</script>
<form class="form-horizontal" role="form" id="myFrm">
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="wizard-step">
</div>
<div class="wizard-step" >
<h3> Step 2</h3>
#Html.Partial("UserView", Model.userViewModel)
<div class="col-md-3"></div>
<div class="col-md-6">
<input type="submit" id="submitButton" class="btn btn-default btn-success" value="Submit" data-bind="click: SubmitForm" />
</div>
<div class="col-md-3"></div>
</div>
<div class="wizard-step">
<h3> Step 3</h3>
</div>
<div class="wizard-step confirm">
<h3> Final Step 4</h3>
</div>
</div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<input type="button" id="back-step" class="btn btn-default btn-success" value="< Back" data-bind="click: Back" />
<input type="button" id="next-step" class="btn btn-default btn-success" value="Next >" data-bind="click: Next" />
</div>
<div class="col-md-3"></div>
</div>
</div>
</form>
I am able to get the data from controller and bind it using knockout. There is a partial view that loads data from controller. But when submitting the updated data, I do not get the data that was updated, instead getting error that "FirstName" property could not be accessed from null reference. I just need to get pointers where I am going wrong especially the right way to create ViewModels and use them.
When you are submitting the form in self.SubmitForm function you are passing Json object which is converted from Knockout view model.
So make sure you are providing the data-bind attributes in all input tags properly. If you are using Razor syntax then use data_bind in Html attributes of input tags.
Check 2-way binding of KO is working fine. I can't be sure as you have not shared your partial view Razor code.
Refer-
http://knockoutjs.com/documentation/value-binding.html
In Chrome you can see what data you are submitting in Network tab of javascript developer console. The Json data that you are posting and ViewModel data structure you are expecting in controller method should match.
You can also change the parameters to expect FormCollection formCollection and check what data is coming from browser when you are posting.

Load partial view in a modal pop-up window using jquery

I have images that are loaded from database. When I click on an image, I want to show that image in a Modal Pop-up. My problem is that, I am not able to call the partial view from jquery. In fact, that action is not getting called from JQuery. Please help... I am a fresher. Below is my code:
_Layout.cshtml
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_Layout</title>
#Styles.Render("~/bundle/ProfileStyle")
#Scripts.Render("~/bundle/JQuery")
#Scripts.Render("~/bundle/JQueryUI")
#Scripts.Render("~/bundle/CustomJS")
</head>
<body>
<div>
#RenderBody()
</div>
<div id="dialog">
#Html.Partial("_ProfileDetail")
</div>
</body>
</html>
Index.cshtml
#model IEnumerable<Profile.Models.TestProfile>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="tableOuterBlock">
#foreach (var item in Model)
{
<div class="tableInnerBlock">
<span>
#*<a href="#Url.Action("Edit", "Profile", new {#item.upi_Id})">*#
<img id="imgOpenDialog" src="#Url.Content(#item.upi_ImgData)" alt="No Image" width="100" height="100" />
#*</a>*#
</span>
</div>
}
</div>
Partial view
#model Profile.Models.TestProfile
<div>
#if(Model != null)
{
<img id="imgOpenDialog" src="#Url.Content(#Model.upi_ImgData)" alt="No Image" width="80%" height="50%" />
}
</div>
JQuery
$(function () {
$("[id*=imgOpenDialog]").click(function () {
var imgDetail = $(this).prop("src");
$("#dialog").dialog({
autoOpen: true,
position: { my: "center" },
modal: true,
resizable: false,
open: function () {
//parameter to c# function
data: { strImg = imgDetail }
$(this).load('#Url.Action("ShowProfileDetail","Profile")');
}
});
});
});
Controller
public PartialViewResult ShowProfileDetail(string strImg)
{
strImg = strImg.Substring(strImg.IndexOf('/'));
List<TestProfile> tpList = db.TestProfiles.Where(x => x.upi_ImgData ==strImg).ToList();
TestProfile testProfile = db.TestProfiles.Find(tpList[0].upi_Id);
return PartialView("_ProfileDetail", testProfile);
}
it may be a bit late but if you check out this blog, and download his code, you will see his use of jquery to create a modal pop up from a partial view.

ASP.NET MVC - DropDownList Validation Problem

I've got two DropDownLists in a form on a page that contain the same values (a list of languages). I want to ensure that the user doesn't select the same value in each of the drop downs.
I've tried using JavaScript to ensure the selected values aren't the same, it works fine but the form submits anyway.
What's the best way to accomplish this?
Here's the code from my View:
<script type="text/javascript">
function CheckLanguageDDL()
{
var form = document.getElementById("form0");
var sourceLangIndex = form.SourceLanguage.selectedIndex;
var targetLangIndex = form.TargetLanguage.selectedIndex;
var strSourceLanguage = form.SourceLanguage.options[sourceLangIndex].text;
var strTargetLanguage = form.TargetLanguage.options[targetLangIndex].text;
if (strSourceLanguage == strTargetLanguage)
{
alert("Source Language and Target Language must be different!");
return;
}
}
</script>
<% Html.BeginForm("Index", "Translate", FormMethod.Post, new { enctype = "multipart/form-data" }); %>
<fieldset>
<legend>Request</legend>
<br />
<div class="editor-label">
<%: Html.LabelFor(m => m.SourceLanguage) %>:
</div>
<div class="editor-field">
<%: Html.DropDownList("SourceLanguage", (IEnumerable<SelectListItem>)ViewData["SourceLanguages"]) %>
<%: Html.ValidationMessageFor(m => m.SourceLanguage) %>
</div>
<br />
<div class="editor-label">
<%: Html.LabelFor(m => m.TargetLanguage) %>:
</div>
<div class="editor-field">
<%: Html.DropDownList("TargetLanguage", (IEnumerable<SelectListItem>)ViewData["TargetLanguages"]) %>
<%: Html.ValidationMessageFor(m => m.TargetLanguage) %>
</div>
<input type="submit" value="Submit Request" onclick="CheckLanguageDDL();" />
</p>
</fieldset>
Thanks.
Make the function return a true/false value that the form submit use that return value
function CheckLanguageDDL()
{
var form = document.getElementById("form0");
var sourceLangIndex = form.SourceLanguage.selectedIndex;
var targetLangIndex = form.TargetLanguage.selectedIndex;
var strSourceLanguage = form.SourceLanguage.options[sourceLangIndex].text;
var strTargetLanguage = form.TargetLanguage.options[targetLangIndex].text;
if (strSourceLanguage == strTargetLanguage)
{
return false;
}
return true;
}
And on the button:
onclick="return CheckLanguageDDL();"

MVC2 Client side validation within Jquery modal dialog

Using MVC2 I currently have a view creating a jquery dialog box containing an Edit partial view. On submit I am looking for it to perform client side validation on the Email class which has a required data annotation attribute for email address. Server side validation works fine but I want the user to have to fix the error in the modal dialog.
Below is the code
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
<div>
<label for="EmailAddress">
Email Address :
</label>
<%= Html.TextBoxFor(model => model.Email.EmailAddress)%>
<%= Html.ValidationMessageFor(model => model.Email.EmailAddress)%>
</div>
Scripts I am loading up are
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.3.2.min.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jqueryUI/js/jquery-ui-1.7.2.custom.min.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Splitter/splitter-1.5.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Scripts/Start.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Scripts/extended/ExtendedControls.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery.validate.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/MicrosoftMvcJQueryValidation.js")%>"></script>
Looking at the html generated I am not getting any of the JSON data generated for the client side validation to work.
Any solutions gladly appreciated. S
I strongly recommend you to use jquery validation script.
jquery.validate.js has all the features for client-side validation within a jquery dialog.
First of all, add the jquery.validate.js to your Site.Master :
<script src="/Scripts/Using/jquery.validate.js" type="text/javascript"></script>
and then write your script something like that :
<script type="text/javascript">
var createLinkObj;
$(function () {
$('#mydialog').dialog({
autoOpen: false,
width: 500,
modal: true,
buttons: {
"OK": function () {
$("#myForm").validate({
rules: {
Name: {
required: true
},
Email: {
required: true,
email: true
}
},
messages: {
Name: " * ",
Email: {
required: " * ",
email: " Invalid e-mail."
}
});
$("#myForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".mylink").click(function () {
//change the title of the dialog
createLinkObj = $(this);
var dialogDiv = $('#mydialog');
var viewUrl = createLinkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
dialogDiv.dialog('open');
});
return false;
});
});
</script>
As you can see when I click the mylink, mydialog appears and before submitting the myForm, I validated the myForm elements namely Name and Email.
Think that your form only contains Name and Email and then you can validate these elments by using jquery validate script.