How to Bind Html Form attribute to Uppy? - asp.net-mvc

I'm trying to get the ImageUrl attribute from Uppy but can't bind it to input asp-for="ImageUrl" type="file" name="file" class="form-control" id="ImageUrl".
When I click on create button,my ImageUrl shows up null in controller method even though I selected a file via Uppy. How can I bind ImageUrl to Uppy and add the file to the folder I created (/tree/test file) ?
<head>
<meta charset="utf-8">
<meta name="viewport">
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no" />
<link href="https://releases.transloadit.com/uppy/v3.1.1/uppy.min.css" rel="stylesheet">
<script src="https://releases.transloadit.com/uppy/v2.12.3/uppy.min.js" type="module"></script>
<script src="https://releases.transloadit.com/uppy/v2.12.3/uppy.legacy.min.js" type="nomodule"></script>
<script src="https://releases.transloadit.com/uppy/locales/v2.1.1/ru_RU.min.js"></script>
</head>
<body>
<form method="post" asp-action="create" id="form2" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="ImageUrl">#localizer.GetLocalizedHtmlString("ImageUrl")</label>
<div id="drag-drop-area">
<input asp-for="ImageUrl" type="file" name="file" class="form-control" id="ImageUrl"/>
</div>
</div>
</br>
<button class="btn btn-primary" type="submit" style="visibility:visible">#localizer.GetLocalizedHtmlString("create")</button>
<a asp-controller="Banner" asp-action="index" class="btn btn-danger">#localizer.GetLocalizedHtmlString("cancel")</a>
</form>
<script>
window.addEventListener('DOMContentLoaded', function () {
'use strict';
var uppy = new Uppy.Core({
debug: true,
autoProceed: false,
locale: Uppy.locales.ru_RU
});
uppy.use(Uppy.Dashboard, {
inline: true,
target: '#drag-drop-area',
showProgressDetails: true,
height: 470,
browserBackButtonClose: false,
hideUploadButton: false
}).use(Uppy.XHRUpload, {
endpoint: '/wwwroot/images/tree/test',
formData: true,
fieldName: 'files[]',
});
uppy.use(Uppy.Form, {
target: 'form',
resultName: 'ImageUrl',
getMetaFromForm: true,
addResultToForm: true,
submitOnSuccess: true,
triggerUploadOnSubmit: true,
});
window.uppy = uppy;
});
</script>
</body>
public async Task Create(Command command,IFormFile? file)
{
string wwwRootPath = _hostEnvironment.WebRootPath;
if (file != null)
{
if (IsImage(file) == true)
{
string fileName = Guid.NewGuid().ToString();
var uploads = Path.Combine(wwwRootPath, #"images\banner");
var extension = Path.GetExtension(file.FileName);
if (command.ImageUrl != null)
{
var oldImagePath = Path.Combine(wwwRootPath, command.ImageUrl.TrimStart('\\'));
if (System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
}
using (var fileStreams = new FileStream(Path.Combine(uploads, fileName + extension), FileMode.Create))
{
file.CopyTo(fileStreams);
}
command.ImageUrl = #"\images\banner\" + fileName + extension;
}
return View();
}
var viewModel = await _mediator.Send(command);
}
return View();
}

Related

Jquery Mobile select Options menu[Phonegap Project]

I get informations about the product name , image, price, category etc from server but i put the informations in a select menus and i want when i change the options of the select menu i display an alert success here is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title>
</head>
<body onLoad="Extra(); " >
<div id="extra" >
</div>
<script type="text/javascript" >
function Extra()
{
var callData = JSON.stringify({"serviceName":"global_functions", "methodName":"getAcces","parameters":[]});
$.post("http://www.test.com/webservice/?contentType=application/json", callData, function(data)
{
$.each(data, function( index, value)
{
$("#extra").append('<div style="border:2px solid red" id="'+index+'"><h3>'+value["name"]+'</h3><img width="200px" src="http://www.test.com/'+value["image"]+'"><select class="comboextra" selected="selected" id="test'+index+'">');
$.each(value["items"],function(index1,value1)
{
$("#test"+index).append('<option prix="'+value1["prix"]+'"cat="'+value1["cat"]+'" value= "'+value1["id"]+'" >"'+value1["name"]+'"</option>');
});
$("#extra").append('</select><label>Quantity</label><input type="number" name="q_extra1" value="0" id="q_extra1" class="quantiteextra" style="width:80px"></div><div class="alert alert-success icon-money"> valeur <span class="totalprix">0</span> </div>')
//alert("test");
});
});
}
$(document).on("change", ".comboextra", function ()
{
alert($(this).find(".comboextra option:selected").attr("prix"));
id = $(this).val();
prix = $("option:selected", this).attr("prix")
qte = $(".quantiteextra").val();
acccat = $("option:selected", this).attr("cat");
total = prix * qte;
acccat = ($(this).find(".comboextra option:selected").attr("cat"));
if (id != 0){$('#finaldata').find("[acccat="+acccat+"]").remove(); $("#finaldata").append('<input type="tex00t" acccat="'+acccat+'" id="acc'+id+'" name="acc['+id+']" value="'+qte+'">');} else {$('#finaldata').find("[acccat="+acccat+"]").remove();}
$(this).find(".totalprix").html(total);
});
</script>
<body>
</html>
//////////////////////////////////////////////EDITED AGAIN//////////////////////////////////
I can now display the alert and i want to select the product from the select menu and add the quantity and calculate the price here is my code after modification it's displaying the alert and the value =0 , it's not calculating and not displaying any value even when i change the quantity and when i change the product:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title>
</head>
<body onLoad="Extra(); " >
<div id="extra" >
</div>
<div id="finaldata"></div>
<script type="text/javascript" >
function Extra()
{
var callData = JSON.stringify({"serviceName":"global_functions", "methodName":"getAcces","parameters":[]});
$.post("http://www.test.com/webservice/?contentType=application/json", callData, function(data)
{
$.each(data, function( index, value)
{
$("#extra").append('<div style="border:2px solid red" id="'+index+'"><h3>'+value["name"]+'</h3><img width="200px" src="http://www.test.com/'+value["image"]+'"><select class="comboextra" selected="selected" id="test'+index+'">');
$.each(value["items"],function(index1,value1)
{
$("#test"+index).append('<option prix="'+value1["prix"]+'"cat="'+value1["cat"]+'" value= "'+value1["id"]+'" >"'+value1["name"]+'"</option>');
});
$("#extra").append('</select><label>Quantity</label><input type="number" name="q_extra1" value="0" id="q_extra1" class="quantiteextra" style="width:80px"></div><div class="alert alert-success icon-money"> valeur <span class="totalprix">0</span> </div>')
//alert("test");
});
});
}
$(document).on("change", ".comboextra", function ()
{
alert($(this).find(".comboextra option:selected").attr("prix"));
id = $(this).val();
prix = $("option:selected", this).attr("prix")
qte = $(".quantiteextra").val();
acccat = $("option:selected", this).attr("cat");
total = prix * qte;
acccat = ($(this).find(".comboextra option:selected").attr("cat"));
if (id != 0){$('#finaldata').find("[acccat="+acccat+"]").remove(); $("#finaldata").append('<input type="tex00t" acccat="'+acccat+'" id="acc'+id+'" name="acc['+id+']" value="'+qte+'">');} else {$('#finaldata').find("[acccat="+acccat+"]").remove();}
$(this).find(".totalprix").html(total);
});
</script>
<body>
</html>
You should bind the change event when you have updated your document. Try adding the binding after you print the selects:
function Extra()
{
var callData = JSON.stringify({"serviceName":"global_functions", "methodName":"getAcces","parameters":[]});
$.post("http://www.test.com/webservice/?contentType=application/json", callData,
function(data)
{
$.each(data, function( index, value)
{
$("#extra").append('<div style="border:2px solid red" id="'+index+'"><h3>'+value["name"]+'</h3><img width="200px" src="http://www.test.com/'+value["image"]+'"><select class="comboextra" selected="selected" id="test'+index+'">');
$.each(value["items"],function(index1,value1)
{
$("#test"+index).append('<option prix="'+value1["prix"]+'"cat="'+value1["cat"]+'" value= "'+value1["id"]+'" >"'+value1["name"]+'"</option>');
});
$("#extra").append('</select><label>Quantity</label><input type="number" name="q_extra1" value="0" id="q_extra1" class="quantiteextra" style="width:80px"></div><div class="alert alert-success icon-money"> valeur <span class="totalprix">0</span> </div>')
});
$(".comboextra").change(function()
{
alert("success");
});
});
}

Access json data using jquery (returned by php)

Q1.here is my html:
<html>
<head>
<title>
Runners
</title>
</head>
<body>
<button id="printrunners"> Print Runners</button>
<div id="printrunnershere"></div>
<script src="printrunners1.js"></script>
</body>
</html>
javascript is here:
$(document).ready(function()
{
$("#printrunners").click(function()
{
$.getJSON("printrunners.php?action=getrunners",
function(json) //also tried without "?action=getrunner" line
{
$.each(json.runners,function()
{
var info= 'Name: '+this['fname']+' '+ this['lname']+' Gender: '+this['gender']+' Finish Time: '+this['finish_time'];
$("#printrunnershere").append(info);
});
});
});
});
printrunners.php here:
<?php
if($_GET) //also tried without it with respect to "?action=getrunner"
{
if($_GET['action']=="getrunners") // also tried without it w.r.t "?action=getrunner"
{
mysql_connect("localhost","runner_db_user","runner_db_user_password");
mysql_select_db("runner_info");
$result=mysql_query("select * from runner");
$runners=array();
while($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
array_push($runners, array('fname' => $row['fname'], 'lname' => $row['lname'], 'gender' => $row['gender'], 'finish_time' => $row['finish_time']));
}
echo json_encode(array("runners" =>$runners));
}
}
?>
Q2. also I used post() to insert a row in same above database it inserts but can't access json data returned by php program:
javascript here:
$(document).ready(function()
{
$('#add').click(function()
{
var data=$("#form1 :input").serializeArray();
$.post($("#form1").attr('action'),data,function(json){
if(json.status=='success')
{
alert (json.message);
}
if(json.status=='fail')
{
alert(json.message);
}
},"json");
});
$("#form1").submit(function()
{
return false;
});
});
it's php here:
<?php
$fname=htmlspecialchars($_POST['fname']);
$lname=htmlspecialchars($_POST["lname"]);
$gender=htmlspecialchars($_POST["gender"]);
$finish_time=htmlspecialchars($_POST["finish_time"]);
$query="insert into runners (fname,lname,gender,finish_time) values('$fname','$lname','$gender','$finish_time')" ;
$result=db_connection($query);
if($result)
{
$msg="Runner " .fname."".lname."added successfully";
success($msg);
}
else
{
fail("insert failed");
}
exit;
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
function db_connection($query1)
{
mysql_connect("localhost","runner_db_user","runner_db_password")
OR die(fail('Could not connect to database.'));
mysql_select_db("runner_info");
return mysql_query($query1);
}
?>
ITS FRONT END(html page):
<!DOCTYPE html>
<html>
<head>
<title>
add runner
</title>
<script src="jquery-2.0.3.js" type="text/javascript"></script>
<script src="jsonuse.js" type="text/javascript"></script>
</head>
<body>
<form id="addrunnerform" name="addrunnerform" method="post" action="addrunner.php">
First Name: <input type="text" name="fname" id="name"></br>
Last Name: <input type="text" name="lname" id="lname"></br>
Gender: <input type="radio" name="gender" id="male" value="m" checked>Male
<input type="radio" name="gender" id="female" value="f">Female</br>
Finish Time: <input type="text" id="finish_time" name="finish_time"></br>
<button type="submit" id="add" name="add">ADD</button>
</form>
</body>
</html>

how to avoid flickering between the pages

I am using jquery mobile and html5.
when i redirect from one page to another page , getting a white screen (flickering).
So how to get out of this problem.
Here is my code..
--Page1--
<html>
<head>
<title>Login</title>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<meta name="x-blackberry-defaultHoverEffect" content="false" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link href="css/jquery.mobile-1.3.1.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.3.1.js" type="text/javascript"></script>
<link href="css/Global.css" rel="stylesheet" />
<script>
/*********Page bind evnet --start--********/
$(document).bind("pageinit", function () {
$("#login").unbind("click").click(function () {
Login();
});
});
/*********Page bind evnet --Ends--********/
var Type;
var Data;
var Url;
var DataType;
var ContentType;
var ProcessData;
var Method;
jQuery.support.cors = true
function Login() {
Type = "POST";
Url = "/login";
Data = '{}';
DataType = "JSON";
ContentType = "application/json; charset=UTF-8";
ProcessData = true;
CallLoginService();
}
function CallLoginService() {
$.ajax({
type: Type,
data: Data,
dataType: DataType,
processData: ProcessData,
url: Url,
contentType: ContentType,
crossDomain: true,
success: function (jsonObj) {
if (jsonObj.GetLoginResult[0].Status == "true") {
$(location).attr('href', 'City.html');
}
else if (jsonObj.GetLoginResult[0].Status == "Invalid username") {
ShowErrorMsg(jsonObj.GetLoginResult[0].Message, '#alertcontainer1');
}
else {
ShowErrorMsg(jsonObj.GetLoginResult[0].Message, '#alertcontainer1');
}
},
error: function (response) {
CheckNetwork();
}
});
</script>
</head>
<body>
<div data-role="page" id="page2" data-theme="a">
<div data-role="header">
<p style="color:#13a5db;"> Login</p>
</div>
<div data-role="content">
<div id="alertcontainer1" >
<div data-role="controlgroup" data-type="horizontal">
<a data-role="button" id="login" data-theme="b">Login</a>
<a data-role="button" href="Registration.html" data-transition="slide" data-theme="b">Register</a>
</div>
</div>
</div>
<div data-role="footer" data-position="fixed">
<p> CopyRight ® 2013</p>
</div>
</div>
</body>
</html>
page2--(city.html) second page
<html>
<head>
<link href="css/jquery.mobile-1.3.1.css" rel="stylesheet" type="text/css"/>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
/*********Page bind evnet --start--********/
$(document).bind("pageinit", function () {
//code
});
/*********Page bind evnet --Ends--********/
</head>
<body>
//code
</body>
</html>

problem with jquery tabs and ajax , behaviour change is observed between tabs eventhough they have similar html

I am working on creating a html page with three tabs, each one of which pulls data from three different html pages through jquery ajax. I am passing 2 parameters , method and mode ( to set read only or edit for all the html elements in the page ) while calling the ajax function.
The problem I have is, when i set the parameters with method=somemethod&mode=ro, the first renders the proper method and in readonly mode, whereas the second tab's html is rendered in edit mode. I debugged the page using firebug but couldnot find the actual problem. All the three tab htmls are all the similar, so i have no idea why this is happening. I have attached the code. Kindly help.
Main html/php page.
<?
$method = $_GET['method'];
$mode = $_GET['mode'];
?>
<html>
<head>
<link type="text/css" href="../../css/ui-lightness/jquery-ui-1.8.14.custom.css" rel="Stylesheet" />
<link type="text/css" href="./methodeditor.css" rel="stylesheet" />
<script type="text/javascript" src="../../js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="../../js/jquery-ui-1.8.14.custom.min.js"></script>
<script>
function loadtabs() {
$( ".tabs" ).tabs({cache:false});
//$( ".tabs" ).tabs();
method = "<? echo $method; ?>";
mode = "<? echo $mode; ?>";
$.ajax({
type: "GET",
url: "oven.php",
data: "method=" +method+"&mode="+mode,
cache: false,
async: true,
success: function(data){
htdata = data;
$("#oven").html(data);
},
});
$.ajax({
type: "GET",
url: "detectors.php",
data: "method=" +method+"&mode="+mode,
async: true,
cache: false,
success: function(data1){
htdata = data1;
$("#detectors").html(data1);
},
});
$.ajax({
type: "GET",
url: "inlets.php",
data: "method=" +method+"&mode="+mode,
async: true,
cache: false,
success: function(data){
$("#inlets").html(data);
},
});
}
</script>
</head>
<body>
<form id="editor" action="method.php" method="POST" >
<div class="editor">
<div class="tabs">
<ul>
<li>Oven</li>
<li>Detectors</li>
<li>Inlets</li>
</ul>
<div id="oven" ></div>
<div id="detectors" ></div>
<div id="inlets"> </div>
</div>
<script>
loadtabs();
</script>
</form>
</div>
</body>
</html>
tab1 php
<?
$method = $_GET['method'];
$mode = $_GET['mode'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Oven</title>
<link type="text/css" href="../../css/ui-lightness/jquery-ui-1.8.14.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="../../js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="../../js/jquery-ui-1.8.14.custom.min.js"></script>
<script>
function togglestatus(val) {
if ( val == "ro" )
{
$('#elements :input').attr('disabled', true );
}
if ( val == "edit")
{
$('#elements :input').removeAttr('disabled');
}
}
function getvalues() {
//file = window.method;
file = "<? echo $method; ?>";
file = "./method/"+file;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", file, false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send("");
xmldoc = xmlhttp.responseXML;
etimenode = xmldoc.getElementsByTagName("method")[0].childNodes[1].childNodes[1];
etime = etimenode.textContent;
document.getElementById("etime").value = etime;
maxovtp = xmldoc.getElementsByTagName("method")[0].childNodes[1].childNodes[5].childNodes[0].data;
document.getElementById("maxovtp").value = maxovtp;
}
</script>
</head>
<body>
<div id="elements">
<input type="checkbox" id="oventemp" value="ON" />Oven Temperature<br />
Equilibrium time <input type="text" id="etime" /><br />
Maximum Oven Temperature <input type="text" id="maxovtp" /><br />
<script>
getvalues();
x = "<? echo $mode; ?>";
togglestatus(x);
</script>
</div>
</body>
</html>
tab2 php/html page
<?
$method = $_GET['method'];
$mode = $_GET['mode'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Detectors</title>
<link type="text/css" href="../../css/ui-lightness/jquery-ui-1.8.14.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="../../js/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="../../js/jquery-ui-1.8.14.custom.min.js"></script>
<script>
function togglestatus(val) {
if ( val == "ro" )
{
$('#elements :input').attr('disabled', true );
}
if ( val == "edit")
{
$('#elements :input').removeAttr('disabled');
}
}
function getvalues() {
file = "<? echo $method; ?>";
file = "./method/"+file;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", file, false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send("");
xmldoc = xmlhttp.responseXML;
heater = xmldoc.getElementsByTagName("method")[0].childNodes[3].childNodes[1].childNodes[1].childNodes[0].data;
document.getElementById("heater").value = heater;
h2flow = xmldoc.getElementsByTagName("method")[0].childNodes[3].childNodes[1].childNodes[3].childNodes[0].data;
document.getElementById("h2flow").value = h2flow;
}
</script>
</head>
<body>
<div id="elements">
Heater Status <input type="checkbox" id="heaterstat" value="ON" /><br />
Heater <input type="text" id="heater" /><br />
H2 Flow <input type="text" id="h2flow" /><br />
<script>
getvalues();
x = "<? echo $mode; ?>";
togglestatus(x);
</script>
</div>
</body>
</html>
I figured out the solution by chance.
Both the tabs had elements wrapped under the same div called . So when toggle status was called , only the first div with id "element" was getting changed. I gave different names to the divs and solved the problem.

Ajax.BeginForm(...) not always working, full postback sometimes, using ASP.NET MVC

I cannot for the life of me figure out why this postback sometimes does an ajax one as it is supposed to and sometimes it does not. Here is the relevant code:
JS:
<html>
<head>
<title>Index</title>
<link href="/Content/screen.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 8]><link href="/Content/ie.css" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/Content/plugins/fancy-type/screen.css" rel="stylesheet" type="text/css" />
<link href="/Content/plugins/buttons/screen.css" rel="stylesheet" type="text/css" />
<link href="/Content/plugins/link-icons/screen.css" rel="stylesheet" type="text/css" media="screen, projection" />
<link href="/Content/jQueryUI/css/cupertino/jquery-ui-1.8.9.custom.css" rel="stylesheet" type="text/css" />
<link href="/Content/HelpDesk.css" rel="stylesheet" type="text/css" />
<link href="/Content/droppy.css" rel="stylesheet" type="text/css" />
<link href="/Content/tablesorter.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.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/jquery.droppy.js" type="text/javascript"></script>
<script src="/Scripts/jquery.cascadingDropDown.js" type="text/javascript"></script>
<script src="/Scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(function () {
$('#nav').droppy();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#targetStartDate").datepicker();
$("#targetEndDate").datepicker();
$("#ticketsHTMLTable").tablesorter({ sortList: [[0, 0], [1, 0]] });
$(".fakeLink").mouseover(function () {
$(this).css("color", "red");
});
$(".fakeLink").mouseout(function () {
$(this).css("color", "black");
});
});
</script>
</head>
Here is my View (Razor):
#using (Ajax.BeginForm("Index", "Problem", new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "ticketsTable",
InsertionMode = InsertionMode.Replace
}))
{
<div class="notice">
<div class="prepend-1 span-2">
<label for="targetPriorityID">
Priority</label>
</div>
<div class="prepend-1 span-3">
<label for="targetStatusID">
Status</label>
</div>
<div class="span-3">
<label for="targetBusinessUnitID">
Business Unit</label>
</div>
<div class="span-3 prepend-1">
<label for="targetStartDate">
Start Date</label></div>
<div class="span-3 prepend-2">
<label for="targetEndDate">
End Date</label></div>
<div class="prepend-1 span-3 last">
&nbsp
</div> <div class="prepend-1 span-2">
#Html.DropDownList("targetPriorityID",
new SelectList(ViewBag.Priorities as System.Collections.IEnumerable,
"ID", "Title"), "All", new { #onchange = " this.form.submit();" })
</div>
<div class="prepend-1 span-3">
#Html.DropDownList("targetStatusID",
new SelectList(ViewBag.Statuses as System.Collections.IEnumerable,
"ID", "Title"),"All", new { #onchange="this.form.submit();" })
</div>
<div class="span-3">
#Html.DropDownList("targetBusinessUnitID",
new SelectList(ViewBag.BusinessUnits as System.Collections.IEnumerable,
"ID", "Title"), "All", new { #onchange = "this.form.submit();" })
</div>
<div class="span-3 prepend-1">#Html.TextBox("targetStartDate", "", new { onchange = "this.form.submit();" })</div>
<div class="span-3 prepend-2">#Html.TextBox("targetEndDate", "", new { onchange = "this.form.submit();" })</div>
<div class="prepend-1 span-3 last">
<input type="submit" value="Hide" />
</div>
<br />
<br />
<br />
</div>
}
<div id="ticketsTable">
#Html.Partial("_AllTickets", Model)
</div>
And finally the controller,
[HttpPost]
public ActionResult Index(int targetPriorityID = -1, int targetBusinessUnitID = -1, int targetStatusID = -1, string targetStartDate = "", string targetEndDate ="")
{
Repository<Priority> priorityRepository = new Repository<Priority>();
Repository<BusinessUnit> businessUnitRepository = new Repository<BusinessUnit>();
Repository<Status> statusRepository = new Repository<Status>();
ViewBag.Priorities = priorityRepository.GetAll();
ViewBag.BusinessUnits = businessUnitRepository.GetAll();
ViewBag.Statuses = statusRepository.GetAll();
var results = problemRepository.GetAll();
results = (targetPriorityID != -1) ? results.Where(t => t.PriorityID == targetPriorityID) : results;
results = (targetBusinessUnitID != -1) ? results.Where(t => t.BusinessUnitID == targetBusinessUnitID) : results;
results = (targetStatusID != -1) ? results.Where(t => t.StatusID == targetStatusID) : results;
results = (targetStartDate != "") ? results.Where(t => t.DateReported >= DateTime.Parse(targetStartDate)) : results;
results = (targetEndDate != "") ? results.Where(t => t.DateReported <= DateTime.Parse(targetEndDate)) : results;
if (Request.IsAjaxRequest())
{
return PartialView("__AllTickets", results);
}
return View(results);
}
Any thoughts?
I would suggest you to use normal form that will be AJAXified later:
#using (Html.BeginForm("Index", "Problem")
{
<div class="notice">
<div class="prepend-1 span-2">
<label for="targetPriorityID">Priority</label>
</div>
<div class="prepend-1 span-3">
<label for="targetStatusID">Status</label>
</div>
<div class="span-3">
<label for="targetBusinessUnitID">Business Unit</label>
</div>
<div class="span-3 prepend-1">
<label for="targetStartDate">Start Date</label></div>
<div class="span-3 prepend-2">
<label for="targetEndDate">End Date</label>
</div>
<div class="prepend-1 span-3 last">
&nbsp
</div>
<div class="prepend-1 span-2">
#Html.DropDownList("targetPriorityID", new SelectList(ViewBag.Priorities as System.Collections.IEnumerable, "ID", "Title"), "All")
</div>
<div class="prepend-1 span-3">
#Html.DropDownList("targetStatusID", new SelectList(ViewBag.Statuses as System.Collections.IEnumerable, "ID", "Title"), "All")
</div>
<div class="span-3">
#Html.DropDownList("targetBusinessUnitID", new SelectList(ViewBag.BusinessUnits as System.Collections.IEnumerable, "ID", "Title"), "All")
</div>
<div class="span-3 prepend-1">
#Html.TextBox("targetStartDate", "")
</div>
<div class="span-3 prepend-2">
#Html.TextBox("targetEndDate", "")
</div>
<div class="prepend-1 span-3 last">
<input type="submit" value="Hide" />
</div>
<br />
<br />
<br />
</div>
}
<div id="ticketsTable">
#Html.Partial("_AllTickets", Model)
</div>
and then in a separate file AJAXify it:
$(function() {
$('form :input').change(function() {
var form = $('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
$('#ticketsTable').html(result);
}
});
});
});
Another improvement I that I would suggest you is to use view models and get rid of ViewData and use strongly typed helpers.
One problem I can see is that your AJAX options in your Razor view specify the GET HTTP method, but the action filter on the controller action specifies POST.
I wonder if Request.IsAjaxRequest() is causing the problem. I would look at removing that code and always return PartialView("__AllTickets", results); instead.

Resources