I'm trying to learn MVC and one the things I want to do is submit a form to an action in my controller and this action will return the submitted data. Sounds simple but I've been trying for hours without any success.
my view:
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
my controller:
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
mRep.Add(ajaxComment);
uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
and my js:
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
You don't need to write any client side code to do this, FYI.
To use the ajax methods successfully in MVC, you will need to do the following. Add this key to appsettings in web.config:
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
As well as include the unobtrusive ajax script:
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Then create div container around your form and replace Html.BeginForm with Ajax.BeginForm
<div id="ajaxReplace">
#using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" }))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
</div>
Then in your controller you'll return something like this:
return PartialView(ajaxComment);
This will save you maintaining a script to do this manually and will funnel you into using the framework as intended. It will also help you out with data annotation validation and all of the juicy stuff that goes with it,
I hope this helps in some way.
Try this:
The Model
public class Comment
{
public string CommentText { get; set; }
public DateTime? DateCreated { get; set; }
public long PostId { get; set; }
public string UserName { get; set; }
}
The View and js
#model SubmitMvcForWithJQueryAjax.Models.Comment
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
#Html.EditorFor(m => m.UserName)
</div>
<div class="editor-text">
#Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} )
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.DateCreated)
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.PostId)
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
var serializedForm = $(this).serialize();
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
data: serializedForm,
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
</script>
The Controller
public class CommentController : Controller
{
//
// GET: /Comment/
public ActionResult Index()
{
return View(new Comment());
}
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
//mRep.Add(ajaxComment);
//uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
}
Basically you are passing javascript object literals directly. So, before you pass data to your controller, it must be in JSON format(because you have specified application/json. see your $.ajax call).
SO, you are missing JSON.stringify()
data: JSON.stringify({
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
}),
OR
var someObj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
/// your other code
data: JSON.stringify(someObj),
// your rest of the code
});
Instead of
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
Try
$('form').submit(function () {
var obj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
...,
data: JSON.stringify(obj),
...,
});
return false;
});
You have to convert data to string before sending it to server. and JSON.stringify does that job
Related
I have an ASP.NET MVC application which has the following form in the view:
#using (Html.BeginForm("Updated", "OnlineEnrollment", FormMethod.Post))
{
<section id="agreement" class="vh-100" style="background-color: #508bfc;">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
<div class="card shadow-2-strong" style="border-radius: 1rem;">
<div class="card-body p-5 text-center scrollHeight">
<h3 class="mb-5">Participant Agreement for Online Enrollment</h3>
<div id="agreenmentDIV" class="myDIV">
<div id="AgreementContent" class="content800">
<button class="btn btn-primary btn-lg btn-block" type="button" id="agreementButton" onclick="return DisplayProgressMessage(this, 'agreement');">I Agree</button>
<button class="btn btn-outline-primary btn-lg btn-block" type="button" id="cancelAgreementButton" onclick="return Cancel(this, 'agreement');">I DO NOT Agree</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="summary" class="vh-100 hideit" style="background-color: #508bfc;">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
<div class="card shadow-2-strong" style="border-radius: 1rem;">
<div class="card-body p-3 text-center scrollHeight">
<h3 class="mb-5">Online Enrollment</h3>
<h5 class="mb-5">Step 3 of 3</h5>
<div id="summaryDIV" class="myDIV">
<div id="summaryContent" class="content800">
<div class="form-outline mb-4">
<label class="form-label text-left width95">
Please review the contribution rate and election selections below.
</label>
</div>
<div class="row width95">
<label class="col-sm-9 col-form-label text-left">Contribution Rate</label>
<label class="col-sm-3 col-form-label text-right" id="summaryRate"> </label>
</div>
<hr width=”75%” align=”center”>
<div id="summaryRow">
< show a summary of the data to be sent to the controller >
</div>
<br />
<button class="btn btn-primary btn-lg btn-block" type="button" id="submitButton" onclick="return SaveData(this, 'confirm');">Confirm</button>
<button class="btn btn-warning btn-lg btn-block" type="button" id="restartButton" onclick="return StartOver(this, 'restart');">Start All Over</button>
<button class="btn btn-outline-primary btn-lg btn-block" type="button" id="cancelSummaryButton" onclick="return Cancel(this, 'cancel');">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
In jQuery, I have this code:
function SaveData(ctl, msg) {
$(".submit-progress").removeClass("hidden");
const myTimeout = setTimeout(function () {
var sendData = [];
var fundName = "";
var percent = $("#electedRate").val();
var fund = 0;
var data = {};
//
// put the contribution rate into the object to send to the controller
// we use fund = 0 to indicate this is the deferral rate
//
data = {
'fund': fund,
'fundName': fundName,
'percent': percent
};
sendData.push(data);
$('.election').each(function () {
percent = parseInt($(this).val());
if (percent > 0) {
fund = $(this).next().val();
fundName = $(this).parent().prev().text();
data = {
'fund': fund,
'fundName': fundName,
'percent': percent
};
sendData.push(data);
}
});
sendData = JSON.stringify(sendData);
console.log(sendData);
$.ajax({
type: "POST",
url: "#Url.Action("SaveElectionData")",
dataType: "text",
data: { 'formData': sendData },
success: function (msg) {
$("#Updated").submit();
},
error: function (req, status, error) {
$("form").submit();
}
});
}, 5);
}
When I run the application, and I look at the console under dev tools, for sendData, I see this:
[
{ "fund": 0, "fundName": "", "percent": "0" },
{ "fund": "66", "fundName": "American Funds 2060 Target Date Fund", "percent": 100 }
]
This is exactly what I anticipated on seeing.
And this is the code in the controller that the ajax should be sending the form data to:
[HttpPost]
public string SaveElectionData(List<FundElection> formData)
{
var returnString = "";
string rateS = "";
var MQMessage = participantSessionData.mqKey + "INTERNET/009EM";
foreach (var record in formData)
{
bool res = false;
int fund = 0;
int pct = 0;
res = Int32.TryParse(record.fund, out fund);
res = Int32.TryParse(record.percent, out pct);
string fundS = fund.ToString();
string pctS = pct.ToString();
if (fund == 0)
{
if (pct < 10)
{
rateS = "0" + pct.ToString();
}
else
{
if (pct == 100)
{
rateS = "99";
}
else
{
rateS = pctS;
}
}
}
else
{
if (fundS.Length == 1 )
{
fundS = "0" + fundS;
}
if (pctS.Length == 1)
{
pctS = "00" + pctS;
}
else
{
if (pctS.Length < 3)
{
pctS = "0" + pctS;
}
}
MQMessage = MQMessage + fundS + pctS;
}
}
< code to update database >
MQMessage = participantSessionData.mqKey + "INTERNET/009RK" + rateS;
participantSessionData = _mqSendRepo.mq6000Send(MQMessage, participantSessionData);
< code to update database >
return returnString;
}
And this is the model for FundElection:
public class FundElection
{
public string percent { get; set; }
public string fund { get; set; }
public string fundName { get; set; }
}
I am getting the following error page:
This site can't be reached.
The webpage at https://localhost:44353/OnlineEnrollment/Updated might be temporarily down or it may have moved permanently to a new web address.
And I never hit the breakpoint that I have set in the controller. The breakpoint is set on the declaration of returnString.
Any ideas why this ajax call does not send data to the controller?
Thanks!
Edit 1: This is a picture of the Payload from the network tab:
for the start you have a wrong url, assuming the controller name is OnlineEnrollment your url should be /OnlineEnrollment/SaveElectionData. Dont stringify sendData, and remove dataType
// sendData = JSON.stringify(sendData);
$.ajax({
type: "POST",
url:"/OnlineEnrollment/SaveElectionData",
//dataType: "text",
data: { formData: sendData},
....
if ajax still doesn't hit an action, try to use an attribute route
[HttpPost("~/OnlineEnrollment/SaveElectionData")]
public string SaveElectionData(List<FundElection> formData)
{
//...
}
or you can use contentType: 'application/json; and stringify data in this case and use FromBody attribute
...
type: 'POST',
url:'/OnlineEnrollment/SaveElectionData',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(sendData),
...
if ajax still doesn't hit an action, try to use an attribute route
[HttpPost("~/OnlineEnrollment/SaveElectionData")]
public string SaveElectionData([FromBody] List<FundElection> formData)
{
//...
}
Try to change $.ajax to following:
$.ajax({
type: "POST",
url: "#Url.Action("SaveElectionData")",
contentType: "application/json",
data: sendData,
success: function (msg) {
$("#Updated").submit();
},
error: function (req, status, error) {
$("form").submit();
}
});
And change method in controller to:
[HttpPost]
public string SaveElectionData([FromBody] List<FundElection> formData)
{
//...
}
In addition replace first line in View component:
#using (Html.BeginForm("Updated", "OnlineEnrollment", FormMethod.Post))
with simple <form> element. Of course, you should add </form> in the end of html. ;)
I am using C# and ASP.NET MVC and try to pass data from the controller to the view. When I debug data show in viewbag but not show in view. The error is undefined. I don't know why this code shows an error.
This is the screenshot:
Screenshot of Debug Result
C# code:
public JsonResult mselectCOACodes(string gl_code)
{
ViewBag.mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (ViewBag.mainCode != "")
{
ViewBag.mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json("", JsonRequestBehavior.AllowGet);
}
jQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="#ViewBag.mainCode" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="#ViewBag.mainDesc" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
Firstly, don't use #ViewBag to store the input value, because you cannot access its value inside your C# code.
Here is C# code:
public JsonResult mselectCOACodes(string gl_code)
{
string mainCode = gl_code.Substring(0, 2) + "-00-00-0000";
if (mainCode != "")
{
string mainDesc = _ICOA.mSelectChartofAccount(ViewBag.mainCode);
}
return Json(mainDesc, JsonRequestBehavior.AllowGet);
}
Here is JQuery:
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#txtvglcode").change(function () {
$.ajax({
type: "GET",
url: "/ChartofAccount/mselectCOACodes",
data: {
gl_code: $("#txtvglcode").val()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (mainDesc) {
$("#txtmainDescription").val(mainDesc);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
View:
<div class="col-sm-6">
<div class="col-sm-3">
<div class="form-group">
<b>Main Code</b>
<div class="form-line">
<input type="text" id="txtglmainCode"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<b>Description</b>
<div class="form-line">
<input type="text" id="txtmainDescription"
value="" class="form-control" placeholder="" />
</div>
</div>
</div>
</div>
Im trying to change a "name" textbox color to (blue if it is male, and pink if it is female) after changing a "gender" dropdown in a partial view.
Index View:
#{
ViewData["Title"] = "Home Page";
var gender = ViewBag.Gender; //breakpoint
}
#if (gender == "Male")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightblue" />
</div>
}
else if (gender == "Female")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightpink" />
</div>
}
else
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: white" />
</div>
}
<div id="gender">
<partial name="_GenderDropdown" model="Model" />
</div>
Partial View:
<label>Gender</label>
<select id="genderstring">
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
//ajax for posting gender to controller
$('#genderstring').on('change', function () {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
data: { gender: $("#genderstring").val() },
success: function () {
},
error: function () {
}
});
});
});
</script>
Controller:
public IActionResult Index(string gender)
{
if(gender == null)
{
return View(new User { Name = "", Gender = "" });
}
else
{
ViewBag.Gender = gender;
return View("Index"); //breakpoint
}
}
With this 2 breakpoints i can see that the data is passing but after I change the gender it gets to the view with the gender in the viewbag but the rest of the page doesen't run.
When you use ajax,it would not reload your page after backend code finishing by default.More detailed explanation and solution you could check as follow:
The first way
You could use .html() method to render the backend result to html after ajax success:
1.View(Be sure add a div to contain the whole html):
<div id="result"> //add the div......
#if (gender == "Male")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightblue" />
</div>
}
else if (gender == "Female")
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: lightpink" />
</div>
}
else
{
<div id="name">
<label asp-for="Name">Name</label>
<input id="nametextbox" type="text" asp-for="Name" style="background-color: white" />
</div>
}
<div id="gender">
<partial name="_GenderDropdown" model="Model" />
</div>
</div>
2.Js in partial view:
<script>
$(document).ready(function () {
$('#genderstring').on('change', function () {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
data: { gender: $("#genderstring").val() },
success: function (res) {
$("#result").html(res); //add this...
},
error: function () {
}
});
});
});
</script>
3.Controller:
You need return PartialView instead of returning View,because if you return view it will generate the layout(e.g the nav bar) again(you could have a try by yourself).
[HttpGet]
public IActionResult Index(string gender)
{
if (gender == null)
{
return View(new User { Name = "", Gender = "" });
}
else
{
ViewBag.Gender = gender;
return PartialView("Index"); //change here...
}
}
Result:
The second way
You could avoid using ajax,just use window.location.href to reload the page(The view and controller are the same as yours,do not change like the first way):
<script>
$(document).ready(function () {
$('#genderstring').on('change', function () {
window.location.href = "/Home/Index?gender=" + $("#genderstring").val();
});
});
</script>
Result:
Note:
If you want to maintain the select list selected item,you may choose the first way,and modify your js like below:
<script>
$(document).ready(function () {
//ajax for posting gender to controller
$('#genderstring').on('change', function () {
var selected_item = $("#genderstring").val(); //add this ....
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'GET',
data: { gender: selected_item },
success: function (res) {
$("#result").html(res);
$("#genderstring").val(selected_item); //add this....
},
error: function () {
}
});
});
});
</script>
Result:
I have this issue with autocomplete, it returns something like this:This
But when you check what returns post method everything is as it should be but in view we get in return just blank field, instead of word "Hardware".
My Code:
Constructuor Method:
[HttpPost]
public JsonResult CreateJS(string prefix)
{
List<CategoryModel> list = new List<CategoryModel>();
list = _context.Categories.ToList();
var CatList = (from N in list
where N.Name.StartsWith(prefix)
select new { value = N.Name,label = N.Name });
return Json(CatList);
View:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#Category").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Incident/CreateJS",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="IncidentDescription" class="control-label"></label>
<input asp-for="IncidentDescription" class="form-control" />
<span asp-validation-for="IncidentDescription" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Category">Cat:</label>
<input type"text" name="Category" id="Category"/>
</div>
There is no need to use $.map in the ajax callback functiom. Directly apply the data to the response.
<script>
$(document).ready(function () {
$("#Category").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Incident/CreateJS",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
});
})
</script>
On the View:
<div id="project-contact-form">
#using (Ajax.BeginForm("Apply","Careers", new AjaxOptions { OnSuccess = "onApplySuccess" }, new { #id = "form1", #enctype = "multipart/form-data" }))
{
<div class="row">
<div class="col-md-12">
<div id="success-project-contact-form" class="no-margin-lr"></div>
</div>
<div class="col-md-6">
<input type="text" required name="Firstname" id="Firstname" placeholder="First name" class="big-input">
</div>
<div class="col-md-6">
<input type="text" required name="Lastname" id="Lastname" placeholder="Last name" class="big-input">
</div>
<div class="col-md-6">
<input type="email" required name="Email" id="email" placeholder="E-mail" class="big-input">
</div>
<div class="col-md-6">
<input type="text" required name="Mobile" id="mobile" placeholder="Mobile" class="big-input">
</div>
<div class="col-md-6">
<input type="file" name="FileUploader" id="files" class="hidden" />
<label for="files" class="float-left cursor-pointer">Upload CV</label>
</div>
<div class="col-md-12 text-center">
<button id="project-contact-us-button" type="submit" class="btn btn-medium btn-transparent-bnsights btn-rounded md-margin-15px-bottom sm-display-table sm-margin-lr-auto">Send</button>
</div>
</div>
}
</div>
In the Controller: HttpPostedFileBase FileUploader value= null i tried several ways but don't know the reason why it is null
public ActionResult Apply(ContactUsModel model, HttpPostedFileBase FileUploader)
{
SendEmail sendemail = new SendEmail();
string toEmail = ConfigurationManager.AppSettings["ContactUsEmail"];
var keys = new Dictionary<string, string>() {
{ "Firstname", model.Firstname },
{ "Lastname", model.Lastname },
{ "Email", model.Email },
{ "Orgnization", model.Orgnization },
{ "Message", model.Message }
};
// string body = $"Firstname : {model.Firstname} \n Lastname : {model.Lastname}\n Email : {model.Email} \n Orgnization : {model.Orgnization} \n Message : {model.Message}";
if (keys != null && keys.Count != 0)
{
string body = string.Join(Environment.NewLine, keys.Select(x => $"{x.Key}: {x.Value}"));
sendemail.Send(new EmailModel()
{
Body = body,
Subject = "Contact Us Message",
To = new List<string>() { toEmail },
}, FileUploader);
return Json(new { val = true }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { val = false }, JsonRequestBehavior.AllowGet);
}
}
Any advice ?
Normally you cannot upload file using Ajax.BeginForm() like Html.BeginForm(). You have to use JavaScript/jQuery to submit the form element.
Here is the solution:
$(document).ready(function(){
$(document).on("submit", "#form1", function (event) {
event.preventDefault();
event.stopImmediatePropagation();
var formData = new FormData(this);
var url = this[0].action;
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (response) {
if (response) {
//do necessary work with response
}
},
error: function() {
//handle error here
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});