Getting the Error 'Not Found' when Mapping Routes - asp.net-web-api

When I try to Map a Route to a Api method call, I only get 'Not Found' in the index.html calling function. I've tried multiple routing template combinations but all get the same error, Not Found. Can anyone help with this?
My Class
public class LogonController : ApiController
{
[HttpPost]
[ActionName("Logon")]
public Boolean Logon(string username, string password)
{
return true;
}
}
My WebApiConfig
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "Logon",
routeTemplate: "api/{controller}/{logon}/{username}/{password}",
defaults: new
{
username = RouteParameter.Optional,
password = RouteParameter.Optional
}
);
}
My Index.html Caller
<div>
<h2>All Products</h2>
<ul id="logon" />
</div>
<div>
<h2>Get User ID</h2>
<input type="text" id="username" size="5" />
<input type="text" id="password" size="5" />
<input type="button" value="Search" onclick="find();" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/logon';
function formatItem(item) {
return 'True';
}
function find() {
var username = $('#username').val();
var password = $('#password').val();
// var email = $('#email').val();
// var firstname = $('#firstname').val();
// var lastname = $('#lastname').val();
// $.getJSON(uri + '/' + username + ',' + password + ',' + email + ',' + firstname + ',' + lastname)
$.getJSON(uri + '/' + username + ',' + password)
.done(function (data) {
$('#logon').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#logon').text('Error: ' + err);
});
}
</script>

I found the answer to my problem. I was going about everything the wrong way. First I was not returning an 'IEnumerable' object.
Next, there was no {action} attribute in my route mapping.
Finally, the request which was coming from an html file was not passing parameters. Here are the changes that were made.
My Class
public class LogonController : ApiController
{
Logon[] log = new Logon[]
{
new Logon { UserName = "Roland", Email = "mike#optonline.net", Password = "test" },
new Logon { UserName = "Yo-yo", Email = "mike#optonline.net", Password = "test" },
new Logon { UserName = "Hammer", Email = "mike#optonline.net", Password = "test" }
};
[ActionName("LogonApi")]
public IEnumerable<Logon> GetThisLogon(string username, string password)
{
var s = log.FirstOrDefault((p) => p.UserName == username);
if (s == null)
{
return log;
}
return log;
}
[ActionName("LogonApi")]
public IEnumerable<Logon> GetLogon()
{
return log;
}
The WebApiConfig
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "LogonApi",
routeTemplate: "api/{controller}/{action}/{username}/{password}",
defaults: new
{
username = RouteParameter.Optional,
password = RouteParameter.Optional
}
);
The JavaScript Call
<div>
<h2>Get User ID</h2>
<input type="text" id="username" size="5" />
<input type="text" id="password" size="5" />
<input type="button" value="Search" onclick="find();" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/logon/LogonApi';
function formatItem(item) {
return 'True';
}
function find() {
var username = $('#username').val();
var password = $('#password').val();
$.getJSON(uri + '/', { username: username, password: password})
.done(function (data) {
$('#logon').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#logon').text('Error: ' + err);
});
}

Related

No response from POST request Spring boot - AJAX

I try to send data from AJAX POST request and don't get an answer, but if I send the exact same request with POSTMAN I do get a response. I don't know what is causing this.
REST Spring boot:
#RestController
public class UsuarioRest {
UsuarioController usuarioController = new UsuarioController();
String token = null;
Usuario usuario = null;
#GetMapping(value = "/hola")
public ResponseEntity<?> login(#RequestBody Usuario user) {
token = usuarioController.login(user.getUser(), user.getPassword());
if (token != null) {
usuario = new Usuario(user.getUser(), user.getPassword());
usuario.setToken();
return new ResponseEntity<Usuario>(usuario, HttpStatus.OK);
} else {
return new ResponseEntity<Error>(new Error(), HttpStatus.BAD_REQUEST);
}
}
AJAX POST:
$(document).ready(
function() {
// SUBMIT FORM
$("#btnEnviar").submit(function(event) {
// Prevent the form from submitting via the browser.
event.preventDefault();
ajaxPost();
});
function ajaxPost() {
// PREPARE FORM DATA
var User = {
id:0,
user : $("#user").val(),
password : $("#password").val(),
token:0
}
console.log(formData);
// DO POST
$.ajax({
type : "GET",
contentType : "application/json",
url : "hola",
data : JSON.stringify(User),
dataType : 'json',
success : function(result) {
console.log(result);
if (result.status == "success") {
$("#resultado").html(
"" + result.data.token
+ "Post Successfully! <br>"
+ "---> Congrats !!" + "</p>");
} else {
console.log(result);
$("#resultado").html("<strong>Error</strong>");
}
},
error : function(e) {
alert("Error!")
console.log("ERROR: ", e);
}
});
}
})
HTML:
<body>
<form id="login">
<input type="text" id="user">
<input type="text" id="password">
<button type="submit" id="btnEnviar" >Enviar</button>
</form>
<div id="resultado">
<button id="hola"></button>
</div>
</body>

Ajax Login from MVC

I have an MVC project that uses the inbuilt forms authentication (which talks to the MDF database stored in App_data). I want to change the login form to be the Ajax login form so that I can take advantage of the "onSuccess" and "onFailure" options.
Does anyone have a working example of how I would achive this as I've tried previuosly but I can't get the form to authenticate it just does nothing. I think I may have missed a step so any help is appreciated.
Example code would also be benificial. Please find my current code below.
The login view
#model MyProject.Models.LoginViewModel
#using (Ajax.BeginForm("Login", "Account", null, new AjaxOptions
{
OnSuccess = "OnSuccess",
OnBegin = "OnBegin",
OnFailure = "OnFailure",
OnComplete = "OnComplete",
HttpMethod = "POST",
UpdateTargetId = "target"
}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Login Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</li>
<li>
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe, new { #class = "checkbox" })
</li>
</ol>
<input type="submit" value="Login" />
</fieldset>
}
Here is the login controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult ValidateUser(string userid, string password,
bool rememberme)
{
LoginStatus status = new LoginStatus();
if (Membership.ValidateUser(userid, password))
{
FormsAuthentication.SetAuthCookie(userid, rememberme);
status.Success = true;
status.TargetURL = FormsAuthentication.
GetRedirectUrl(userid, rememberme);
if (string.IsNullOrEmpty(status.TargetURL))
{
status.TargetURL = FormsAuthentication.DefaultUrl;
}
status.Message = "Login attempt successful!";
}
else
{
status.Success = false;
status.Message = "Invalid UserID or Password!";
status.TargetURL = FormsAuthentication.LoginUrl;
}
return Json(status);
}
Here is the login view model
public class LoginStatus
{
public bool Success { get; set; }
public string Message { get; set; }
public string TargetURL { get; set; }
}
Script on the page for handling the form
$(document).ready(function () {
$("#login").click(function () {
$("#message").html("Logging in...");
var data = {
"UserName": $("#userid").val(),
"Password": $("#password").val(),
"RememberMe": $("#rememberme").prop("checked")
};
$.ajax({
url: "/Home/Index",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (status) {
$("#message").html(status.Message);
if (status.Success)
{
window.location.href = status.TargetURL;
}
},
error: function () {
$("#message").html("Error while authenticating user credentials!");
}
});
});
});
I've an extensions (MvcNotification) that put into ViewData or TempData messages to display.
To complement this, my post actions return "ERROR" or "OK" and i use those messages inside the ajax form OnSuccess.
MessageType
public enum MessageType
{
Success,
Warning,
Error,
Info
}
AjaxMessagesFilter
/// <summary>
/// If we're dealing with ajax requests, any message that is in the view data goes to the http header.
/// </summary>
public class AjaxMessagesFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewData = filterContext.Controller.ViewData;
var response = filterContext.HttpContext.Response;
foreach (var messageType in Enum.GetNames(typeof(MessageType)))
{
var message = viewData.ContainsKey(messageType)
? viewData[messageType]
: null;
if (message != null) // We store only one message in the http header. First message that comes wins.
{
response.AddHeader("X-Message-Type", messageType.ToLower());
response.AddHeader("X-Message", HttpUtility.HtmlEncode(message.ToString()));
return;
}
}
}
}
}
ControllerExtensions
public static class ControllerExtensions
{
public static ActionResult ShowMessage(this Controller controller, MessageType messageType, string message, bool showAfterRedirect = false, bool UseJson = false)
{
var messageTypeKey = messageType.ToString();
if (showAfterRedirect)
{
controller.TempData[messageTypeKey] = message;
}
else
{
controller.ViewData[messageTypeKey] = message;
}
if (UseJson)
return new JsonResult() { Data = "ERROR", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
else
return new ContentResult() { Content = "ERROR" };
}
public static ActionResult ShowMessage(this ControllerBase controller, MessageType messageType, string message, bool showAfterRedirect = false, bool UseJson = false)
{
var messageTypeKey = messageType.ToString();
if (showAfterRedirect)
{
controller.TempData[messageTypeKey] = message;
}
else
{
controller.ViewData[messageTypeKey] = message;
}
if (UseJson)
return new JsonResult() { Data = "ERROR", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
else
return new ContentResult() { Content = "ERROR" };
}
public static ActionResult EmptyField(this Controller controller, string FieldName, bool IsJson = false)
{
controller.ShowMessage(MessageType.Info, String.Format("O campo \"{0}\" é de carácter obrigatório.", FieldName));
return IsJson == false ? (ActionResult)new ContentResult() { Content = "ERROR" } : (ActionResult)new JsonResult() { Data = "ERROR", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
To call the extension inside the controller:
this.ShowMessage(MessageType.Error, "An error has occurred");
if you want to redirect after the message is thrown, you need to add true in the last parameter.
this.ShowMessage(MessageType.Error, "An error has occurred", true);
Note: I created the EmptyField method to give a standart message when some field is empty.
Action Example (LoginPost)
[HttpPost]
[AllowAnonymous]
public ActionResult LoginPost(LoginViewModel model, string returnUrl, bool Relogin = false)
{
returnUrl = string.IsNullOrEmpty(returnUrl) || string.IsNullOrWhiteSpace(returnUrl) ? "/" : returnUrl;
if (string.IsNullOrEmpty(model.UserName))
return this.EmptyField(Resource_General.UserName);
if (string.IsNullOrEmpty(model.Password))
return this.EmptyField(Resource_General.Password);
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = SignInManager.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var user = db.Users.FirstOrDefault(x => x.UserName == model.UserName);
if (!user.IsActive)
{
AuthenticationManager.SignOut();
this.ShowMessage(MessageType.Error, Messages.LockedOutUser);
return Content("ERROR");
}
if (Url.IsLocalUrl(returnUrl))
return Content(returnUrl);
else
return Content("/Home");
case SignInStatus.LockedOut:
this.ShowMessage(MessageType.Error, Messages.LockedOutUser);
return Content("ERROR");
case SignInStatus.RequiresVerification:
case SignInStatus.Failure:
default:
this.ShowMessage(MessageType.Error, Messages.WrongPassword);
return Content("ERROR");
}
}
Ajax Form
#using (Ajax.BeginForm("LoginPost", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, new AjaxOptions { OnSuccess = "OnSuccess" }, new { #id = "login-form" }))
{
#Html.AntiForgeryToken()
<div class="network-login-fields">
<div class="form-group">
<div class="input-group col-xs-12">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", placeholder = Resource_General.UserNamePlaceHolder, name = "loginname", autofocus = "true" })
</div>
</div>
<div class="form-group">
<div class="input-group col-xs-12">
#Html.PasswordFor(m => m.Password, new { #class = "form-control", placeholder = Resource_General.PasswordPlaceHolder, name = "password" })
</div>
</div>
<div class="network-login-links">
<button class="btn btn-default"><i class="fa fa-sign-in"></i> #Resource_General.Login</button>
</div>
</div>
}
Javascript
function OnSuccess(data) {
if (data != "ERROR") {
window.location.href = data;
}
}
Here in the javascript, you need to handle the ajax form OnSuccess and do something if the response is "OK" or "ERROR".
In your main javascript file you need to include this:
Handle Messages
// START Messages and Notifications
function handleAjaxMessages() {
$(document).ajaxStart(function () {
Openloading();
}).ajaxComplete(function (e, xhr, settings) {
CloseLoading();
}).ajaxSuccess(function (event, request) {
checkAndHandleMessageFromHeader(request);
}).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (thrownError !== "abort") {
CloseLoading();
NotifyError();
}
OnInit();
});
}
function checkAndHandleMessageFromHeader(request) {
var msg = request.getResponseHeader('X-Message');
if (msg) {
var title = NotifyHeader(request.getResponseHeader('X-Message-Type'));
Notify(msg, title, request.getResponseHeader('X-Message-Type'));
}
}
function NotifyHeader(type) {
console.log(type);
var title = "";
if (type == "error")
title = CustomScriptsLocales.ErrorTitle;
if (type == "success")
title = CustomScriptsLocales.SuccessTitle;
if (type == "warning")
title = CustomScriptsLocales.WarningTitle;
if (type == "info")
title = CustomScriptsLocales.InfoTitle;
console.log(title);
return title;
}
function Notify(message, title, type) {
if (title == null || title == "" || title == undefined) {
title = NotifyHeader(type);
}
PNotify.desktop.permission();
var notice = new PNotify({
title: title,
text: decodeHtml(message),
nonblock: {
nonblock: true,
nonblock_opacity: .55
},
buttons: {
closer: true,
},
desktop: {
desktop: false,
},
hide: true,
type: type,
delay: 2000,
insert_brs: true,
remove: true,
});
}
function NotifyError() {
Notify(CustomScriptsLocales.ErrorMessage, CustomScriptsLocales.ErrorTitle, "error");
}
// END Messages and Notifications
And call it inside a ready function:
$(document).ready(function () {
handleAjaxMessages();
}
Note: I use the PNotify plugin to show notifications. If you don't want notifications just exclude all this javascript "Handle Messages".

Ajax doesn't call method in production

This is probably something simple, but I can't find what is wrong to give me this problem.
I have a form in a HTML page that calls, on click, a method in a controller via Ajax. It works perfectly in my development machine, but when I put it in production environment the call never gets to the controller. Anyone have any ideas why? I've seen many questions like this, most of them saying it's most likely a problem with the action path, but I've tried a lot of diferent ways to call it (with razor html helpers, passing the absolute path, etc) and got nothing.
The form (simple):
<form action="/Home/SendMail/" id="contactForm" type="post">
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<input type="text" name="subject" id="subject">
<textarea name="message" id="message"></textarea>
<input type="submit" value="Enviar Mensagem">
</form>
The ajax call:
$("#contactForm").validate({
submitHandler: function(form) {
var submitButton = $(this.submitButton);
submitButton.button("loading");
var url = $("#contactForm").attr("action");
$.ajax({
type: "POST",
url: url,
data: {
"name": $("#contactForm #name").val(),
"email": $("#contactForm #email").val(),
"subject": $("#contactForm #subject").val(),
"message": $("#contactForm #message").val()
},
dataType: "json",
success: function (data) {
if (data.response == "success") {
$("#contactSuccess").removeClass("hidden");
$("#contactError").addClass("hidden");
$("#contactForm #name, #contactForm #email, #contactForm #subject, #contactForm #message")
.val("")
.blur()
.closest(".control-group")
.removeClass("success")
.removeClass("error");
if(($("#contactSuccess").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactSuccess").offset().top - 80
}, 300);
}
} else {
$("#contactError").removeClass("hidden");
$("#contactSuccess").addClass("hidden");
if(($("#contactError").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactError").offset().top - 80
}, 300);
}
}
},
The controller method:
public class HomeController : Controller
{
[HttpPost]
public JsonResult SendMail(string name, string email, string subject, string message)
{
try
{
string emailTo = "myemail#example.com";
MailMessage Email = new MailMessage();
Email.From = new MailAddress("mail#example.comr");
string[] emailsDestinarios = emailTo.Split(';');
foreach (string emailDestinatario in emailsDestinarios)
{
Email.To.Add(new MailAddress(emailDestinatario));
}
Email.Subject = subject;
Email.IsBodyHtml = true;
Email.Body = DateTime.Now.ToString() + "<br />" + name + "<br />" + email + "<br /><br /><b>" + subject + "</b><br /><br />" + message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("mail#example.com", "mypassword");
smtp.Send(Email);
return Json(new { response = "success" });
}
catch (Exception ex)
{
return Json(new { response = ex.Message });
}
}
}
It works fine in development, but not in production environment.

How can I Authenticate with ServiceStack using jQuery Ajax

I'm trying to do something like the following:
jQuery Part:
function ajaxLogin() {
$.ajax({
url: "auth/credentials",
type: "POST",
data: { UserName: $("#form_username").val(), Password: $("#form_pwd").val() },
success: function (data) {
$("#login_div").hide();
},
error: function (jqXHR,textStatus,errorThrown) {
$("$login_msg").text(errorThrown);
}
});
}
However, for some reason it's always coming back to the success function and data contains the html contents of the current html document.
My ServiceStack AuthProvider contains the following TryAuthenticate:
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var session = authService.GetSession();
string error = null;
try
{
var dataSource = authService.TryResolve<RiskViewDataSource>();
var diModelInstance = dataSource.diModelRootObject;
string authResult = UserFactory.authenticate(session.Id, userName, password, false);
if ("OK".Equals(authResult))
{
session.IsAuthenticated = true;
session.UserName = session.DisplayName = userName;
session.UserAuthId = password;
UsersManager.generateUsersPolicies();
UsersManager.loadUserPolicies();
return true;
}
else
{
session.IsAuthenticated = false;
session.UserName = session.DisplayName = null;
session.UserAuthId = null;
authService.RemoveSession();
return false;
}
}
catch (Exception e)
{
Log.Error(e.ToString());
session.IsAuthenticated = false;
session.UserName = session.DisplayName = null;
session.UserAuthId = null;
error = "Could not connect to RiskView database";
}
if (error != null)
{
throw HttpError.Unauthorized(error);
}
else
{
return false;
}
}
Ok, after a day of messing about I've come up with this solution which works for me. I had to create a new service request for logging in. I called it RenewSession.
Service Stack Part:
[Route("/RenewSession", "POST")]
public class RenewSessionRequest : IReturn<RenewSessionResponse>
{
}
public class RenewSessionResponse : IHasResponseStatus
{
public RiskViewJsonObject Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class RenewSessionService : Service, IPost<RenewSessionRequest>
{
public object Post(RenewSessionRequest request)
{
string username = this.Request.GetParam("UserName");
string password = this.Request.GetParam("Password");
string message = "";
IAuthProvider authService = AuthService.GetAuthProvider("credentials");
Boolean success = false;
try
{
var response = authService.Authenticate(this, this.GetSession(), new Auth { UserName = username, Continue = null, Password = password });
success = true;
}
catch (Exception e)
{
message = e.ToResponseStatus().Message;
}
return new RenewSessionResponse { Result = new Mapping.RiskViewJsonObject("{ \"success\" : " + (success ? "true" : "false") + ", \"message\" : \"" + RiskViewJsonObject.cleanForJSON(message)+ "\" }") };
}
}
Html and Ajax Part:
1) Add a div to the page for the login details (Hide it to start with)
<div id="login-div" style="position:absolute;display:hidden;left:100;top:100;background-image:url('images/login_bk.png');">
<p id="login_error_msg"></p>
<form id="login_form" onsubmit="loginSubmit(); return false;">
<table>
<tr>
<td>Username:<input id="in_un" type="text" name="UserName" autocomplete="off" autocorrect="off" autocapitalize="off"/></td>
</tr>
<tr>
<td>Password:<input id="in_pw" type="password" name="Password" autocomplete="off" autocorrect="off" autocapitalize="off"/></td>
</tr>
<tr>
<td style="text-align: center;">
<input id="login_submit" type="submit" class="hand_cursor" value="Login">
</td>
</tr>
</table>
</form>
</div>
2) I add 401 checks to every ajax query on my page (401 tells us that the session has expired)
$.getJSON('/Menus?format=json', function(data) {
// Do some stuff
}).fail(function (jqxhr,textStatus,error) {
if (jqxhr.status == 401) {
loginAgain();
}
});
3) Show the div to re-login
function loginAgain(reloadMenu) {
$("#login-div").show("slow");
}
4) The onclick for login button or onsubmit event for the login form
function loginSubmit() {
if ($("#in_un").val().trim() == "" || $("#in_pw").val().trim() == "") {
$("#login_error_msg").text("Username or Password is still empty.");
return false; // Prevent form from submitting
} else {
$("#login_submit_btn").attr("disabled","disabled");
$("#login_error_msg").text("");
$.ajax({
url: "/RenewSession?format=json",
type: "POST",
data: { UserName: $("#in_un").val(), Password: $("#in_pw").val() },
success: function (data, textStatus, jqXHR) {
$("#login_submit_btn").removeAttr("disabled");
if (data.Result.success) {
$("#login-div").hide();
} else {
if (data.Result.message) {
$("#login_error_msg").text(data.Result.message);
} else {
$("#login_error_msg").text(textStatus);
}
$("#in_pw").focus();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$("#login_submit_btn").removeAttr("disabled");
$("#login_error_msg").text("ERROR: "+errorThrown);
$("#in_pw").focus();
}
});
}
return false; // Stop the form submiting, we're just gonna hide the div
}

How would I pass a value via a ajax form post in MVC3?

I have the ability to upload a file and save it to a directory. That is all good. I need to make an entry to my database with information about that file. So far I am not sure how to pass a value from the view to the controller in this particular case. I have tried to pass it as a method parameter but the value is not getting posted.
Here is my Razor form:
#using (Html.BeginForm("AjaxUpload", "Cases", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
{
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
}
<div id="attachments">
#Html.Partial("_AttachmentList", Model.Attachments)
</div>
Here is my jQuery to ajaxify the form:
$(function () {
$('#ajaxUploadForm').ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$('#ajaxUploadForm').block({ message: '<h1><img src="/Content/images/busy.gif" /> Uploading file...</h1>' });
},
success: function (result) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, result.message);
//$('#attachments').html(result);
},
error: function (xhr, textStatus, errorThrown) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
Here is the controller method:
public FileUpload AjaxUpload(HttpPostedFileBase file, int cid)
{
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
var attach = new Attachment { CasesID = cid, FileName = file.FileName, FileType = file.ContentType, FilePath = "Demo", AttachmentDate = DateTime.Now, Description = "test" };
db.Attachments.Add(attach);
db.SaveChanges();
//TODO change this to return a partial view
return new FileUpload { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I would like cid to be passed to this method so that I can insert a record into the database.
You could include it as a hidden field inside the form:
#Html.Hidden("cid", "123")
or as a route value:
#using (Html.BeginForm(
"AjaxUpload",
"Cases",
new { cid = 123 },
FormMethod.Post,
new { enctype = "multipart/form-data", id = "ajaxUploadForm" }
))
{
...
}

Resources