I currently have a partial view that renders at the top of every page on the site. The point of this partial view is to provide a form that lets the user do a quick search. I have set the partial view form up as follows:
#using (Html.BeginForm())
{
<div class="col-md-7" style="text-align: right">
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.TextBox("caseReference")
<button type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
}
#Html.Partial("_MainNavigation")
</div>
</div>
</nav>
<script type="text/javascript">
$(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var request = { caseReference: $('#caseReference').val() };
submitForm(request, '#Url.Action("CaseSearch", "QuickSearch", new { area = "Search" })');
});
});
</script>
However under the page source the form action renders as a request to the home page with a post action. I have read numerous examples and this task seems very straight forward. Would it be a better idea to use the parameters on the #html.BeginForm() method?
So after spending a few hours researching, I have finally got the quick search functionality to work on the home page of my site. In the razorview I have the following code:
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.Kendo().MaskedTextBox().Name("name").Mask("000000/0000").Deferred()
<button id="search" type="submit">
<i class="fa fa-search"></i>
</button>
<script type="text/javascript">
$(function () {
$("#search").on("click", function (event) {
event.preventDefault();
var value = $('#name').val();
value = value.replace(/[/]/g, "_");
var refVal = value;
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
$.ajax({
type: 'GET',
url: url,
cache: false,
dataType: 'json',
contentType: "application/json;",
success: function (result) {
if (result.success) {
window.location.href = result.url;
}
else {
bootbox.alert(result.message);
}
}
});
});
});
However in regards to the following line:
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
If I hard code the url and append the search term it works on the Home page because we are at the root directory but from other pages it fails, To get around this I tried to use #Url.Action. However this is producing the following result in the html soure code:
var url = '' + '//' + refVal;
Is there a certain way to use the URL.Action method from withing JS?
Related
I cannot get the following piece of code to fire the button click to call save. I am using ASP.Net MVC with Knockoutjs. I am new to knockout and mvc. What am I missing here? Thanks in advance.
cshtml
#section scripts
{
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/CustomScripts/bookingviewmodel.js"></script>
<script type="text/javascript">
var bookingViewModel = new BookingViewModel(#Html.Raw(data));
ko.applyBindings(bookingViewModel);
</script>
}
<div class="content">
<button class="btn btn-primary pull-right" data-bind="click: save"><i class="fa fa-check"></i> Save Booking</button>
</div>
bookingviewmodel.js
BookingViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.save = function () {
$.ajax({
url: "/Booking/Save",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json",
success: function (data) {
if (data.bookingViewModel != null) {
ko.mapping.fromJS(data.bookingViewModel, {}, self);
}
}
});
}
}
I fail to upload pictures using formdata. This is my previous code which was working fine(This is just part of a form):
<div class="fileinput fileinput-new" data-provides="fileinput" style="width: 100%;">
<div class="fileinput-preview" data-trigger="fileinput" style="margin: 10px 0px;"></div>
<div>
<span class="btn btn-default btn-file">
<input type="file" id="filePicture" name="filePicture">
</span>
</div>
</div>
And this is my Ajax call:
$(document).on("click", "#sledBuckSaveBtn", function() {
event.preventDefault();
event.stopPropagation();
var fd = new FormData(document.getElementById("saveSledBuckForm1"));
$.ajax({
type: "POST",
url: "/SledBuck/EditFromSledTestDetails", //url,
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function (result) {
var title = "Error", msgtype = "error";
if (result) {
title = "Success";
msgtype = "success";
}
document.location.reload();
}
});
});
But my requirement has changed, I need to use Krajee plugin to create an input type:
Here my new code:
<div class="col-md-9">
<input id="input-#Model.PictureIdList[i]" type="file" class="file" data-show-upload="false" data-show-caption="true" data-input-id="#Model.PictureIdList[i]">
</div>
what problem am I facing. I think the reason is I might need to do configuration for Krajee plugin but I'm not sure. Any suggestions?
I just found the answer. I lacked the name of the file input. Just do like this and the file will be regconized:
<input id="input-#Model.PictureIdList[i]" name= "fileInput" type="file" class="file" data-show-upload="false" data-show-caption="true" data-input-id="#Model.PictureIdList[i]">
I am trying to get the model binder to recognize the change. I am not sure what I am missing here. Basically the initial page population pulls the page number from the database. I then have the sortable working, the raw HTML in Firebug shows the change in order. But when I post back to the model first off it is not figuring out to go the post method and the other issue is Survey. Pages does not seem to have the change in order.
View
#for (var i = 0; i < Model.Pages.Count; i++)
{
var page = Model.Pages.ElementAt(i);
#Html.Hidden("Pages[" + i + "].PageId", page.PageId, new { #class = "page_index" })
#Html.Hidden("Pages[" + i + "].PageNumber", page.PageNumber)
<li id="#page.PageId" class="sortable-item text-center ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s">
</span>#page.PageNumber</li>
}
</ul>
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('.sortable').sortable({
stop: function (event, ui) {
var formData = $('#editSurveryForm').serialize();
$.ajax({
url: "#Url.Action("Edit")",
data: formData,
type: 'POST',
traditional: true,
success: function () {
alert("success");
},
error: function () {
alert("fail");
}
}
);
}
});
});
</script>
Controller
[HttpPost]
public ActionResult Edit(Survey survey)
{
if (!ModelState.IsValid)
{
return View("EditSurvey", survey);
}
surveyRepository.UpdateSurvey(survey);
return RedirectToAction("Index", "Administration");
}
Ok, I figure this one out. I had the hidden fields outside of the <li></li> tag. Once I moved them inside I did all my logic as I would have.
<div class="span9">
<div class="span4">
<ul class="sortable_page_list">
#for (var i = 0; i < Model.Pages.Count; i++)
{
<li class="sortable-item text-center ui-state-default">
#Html.HiddenFor(model => model.Pages[i].PageId)
#Html.HiddenFor(model => model.Pages[i].PageNumber)
<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>#Model.Pages[i].PageNumber
</li>
}
</ul>
<div class="span1 pull-right internal-wrapper">
#Html.ActionLink("Add", "AddPage", new { id = Model.SurveyId }, new { #class = "add_survey_icon common_icon_settings" })
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.sortable_page_list').sortable({
update: function (event, ui) {
var counter = 1;
$("[id*='PageNumber']").each(function() {
$(this).attr("value", counter);
counter++;
});
//var surveyToUpdate = $('#editSurveyForm');
$.ajax({
url: '#Url.Action("Edit","Administration")',
contentType: "application/json; charset=utf-8",
data: $('#editSurveyForm').serialize(),
type: 'POST'
});
}
});
});
Last thing to figure out is why the ajax post is not posting to the Post method with the survey form data
I'm working on a single page application using jquery mobile along with knockout.js binding on MVC4 platform..
This is my button on the main div page:
<div data-role="page" id="pageMain">
<div data-role="content">
View Invoices
</div>
</div>
This is my target div page:
<div data-role="page" id="pageExisting">
<div data-role="header">
<h1>Existing Invoices's</h1>
<a data-rel="back" data-role="button">Back</a>
</div>
<div class="choice_list" data-role="content" data-bind="visible: Headers().length > 0">
<ul id="headersList" data-role="listview" data-bind="foreach: Headers" data-filter-placeholder="Search Invoice" data-filter-theme="a" data-inset="true"
data-filter="true" data-theme="b">
<li>
<a href="#" data-inline="true">
<h2>Invoice No.: <span data-bind="text: inv_no"></span></h2>
<p>Amount.: <span data-bind="text: inv_amt"></span></p>
</a>
</ul>
</div>
</div>
Here is the script section:
var HeaderViewModel = function () {
//Make the self as 'this' reference
var self = this;
self.Headers = ko.observableArray([]);
function GetHeaders() {
//Ajax Call Get All Employee Records
// self.GetHeaders = function () {
$.ajax({
type: "GET",
url: "/api/InvAPI",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.Headers(data);
},
complete: function () {
$.mobile.changePage("#pageExisting");
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
}
self.GetHeader = function () {
GetHeaders();
}
};
$(document).ready(function () {
ko.applyBindings(new HeaderViewModel());
}
When I hit the button "view Invoices" I get a typical Jquery mobile formated listview
but the problem is when I hit the back button and navigate again to the "PageExisiting" div Page I get the list data with no styling..
When viewing page source in both cases, I noticed that on second navigation;
Li tags have not attributes.
I have tried some solutions like: listview refresh, page destroy, page create prior to the line:
$.mobile.changePage("#pageExisting");
with no luck.
I'm stuck here guys and I will appreciate your proposed solutions
Thanks
Refresh list view before showing the page.
$('#pageID').on('pagebeforeshow', function() {
$('[data-role=listview]').listview('refresh');
});
I am trying to write jquery function that will pop up and say Post was successful! and if not, Post was not successful! How could I use a try catch with inputting some jquery?
#using (Html.BeginForm("Admin", "Home", "POST"))
{
<div class="well">
<section>
<br>
<span style="font-weight:bold">Text File Destination: </span>
<input type="text" name="txt_file_dest" value="#ViewBag.GetTextPath">
<span style="color:black"> Example:</span><span style="color:blue"> \\invincible\\chemistry$\\</span>
<br>
<br>
<span style="font-weight:bold">SQL Connection String:</span>
<input type="text" name="sql_Connection" value="#ViewBag.GetSqlConnection">
<span style="color:black"> Example:</span> <span style="color:blue"> Server=-</span>
<br>
<br>
<button class="btn btn-success" type="submit" >Save Changes</button>
</section>
</div>
}
So I figured out my answer. Just for future reference to anybody that tries this, below is what I did. I placed it above #using (Html.BeginForm("Admin", "Home", "POST")). #Andrew I did try yours, but I could not get it to work. Thanks to everyone for tyring to help me.
<script language="javascript" type="text/javascript">
$(function() {
$("form").submit(function(e) {
$.post($(this).attr("action"), // url
$(this).serialize(), // data
function (data) { //success callback function
alert("Edit successful");
}).error(function () {
alert('failure');
});
e.preventDefault();
});
});
</script>
You'll want to change your HtmlHelper BeginForm declaration slightly, so that an id attribute will be rendered with the element, like this:
#using (Html.BeginForm("Admin", "Home", FormMethod.Post, new { id = "well-form" }))
Now you can add a script above the declaration which traps-and-submits the form and handles the response (success or error).
<script>
$(function() {
// Find the form with id='well-form'
$('#well-form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('Post was successful!');
},
error: function(result) {
alert('Post was not successful!');
}
});
// return false to cancel the form post
// since javascript will perform it with ajax
return false;
});
});
</script>
$.ajax({
url: 'post.html',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
Compounding to Sonu's answer, I have found similar questions regarding this hard to accomplish as the HTML form submit has no callback and it seems that it is recommended to use ajax() when you want a postback confirmation of your form submission.
Please see this Stackoverflow Link.
Could you use the Ajax Events? such as $.ajaxSuccess
http://api.jquery.com/category/ajax/global-ajax-event-handlers/