Asp.net MVC-fileupload value shows null values in httppost method - c#

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;
});
});

Related

How to call asp.net mvc form submit event which use ajax after button click and validate?

I'm developing an application with asp.net mvc. I am not doing a screen for preparing questions for surveys and answers to these questions. On the home screen is a table of questions. When I press 'add new question' button, I open a popup with jquery and add the question and answer options in this question ('popup is independent of the main screen, ie Layout = null'). Then, when the 'submit' button of this popup is pressed, I validate the form in the popup with javascrit in addOrEdit.cshtml. If the validation is successful, my goal is to submit the form submit event of asp.net mvc to the javascript function on the main page. I can't do this. Where am I making a mistake. What is the problem. I tried to explain it in an explanatory way. I also added screenshots and codes.
Index.cshtml
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Add Question</h2>
<a class="btn btn-success" style="margin-bottom: 10px" onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Add New Question</a>
//table heree
Index.cshtml sectionscript
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
//datatable script hereee.....
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
alert('gel babanaaa');
if ($(form).valid()) {
alert('validd');
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
showDuration: 500,
gap: 1000
});
}
}
});
}
}
</script>
}
AddOrEdit.cshtml
#model MerinosSurvey.Models.Questions
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { #class = "needs-validation", novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id = "questionForm" }))
{
// other component heree
<div class="form-group row">
<input type="button" value="Submit" class="btn btn-primary" id="btnSubmit" />
<input type="reset" value="Reset" class="btn btn-secondary" />
</div>
}
AddOrEdit.cshtml scripts
<script>
//some scriptt for validationn...
$("#btnSubmit").click(function (event) {
var form = $("#questionForm");
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.addClass('was-validated');
// Perform ajax submit here...
if ($(form).valid()) {
form[0].submitEvent();//MY PROBLEM!!!!!
}
});
</script>
I want to call SubmitForm event in asp.net mvc after button click and validation. And I used form[0].submitEvent(); SO I can't send a request via AJAX. but I doesn't work.
replaces your Index.cshtml with the code below
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Add Question</h2>
<a class="btn btn-success" style="margin-bottom: 10px" onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Add New Question</a>
<table id="questionTable" class="table table-striped table-bordered accent-blue" style="width: 100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Detay/Güncelle/Sil</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ width: '10%', targets: 5 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function (data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function (data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function (data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni anket oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
alert('Submit Formm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.addClass('was-validated');
if ($(form).valid()) {
alert('ben burdyaım');
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
replaces your AddOrEdit.cshtml with the code below
#model MerinosSurvey.Models.Questions
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { #class = "needs-validation", novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id = "questionForm" }))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group row">
#Html.LabelFor(model => model.QuestionId, new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.QuestionId, new { #readonly = "readonly", #class = "form-control" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(model => model.QuestionName, new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { #class = "form-control", required = "true" } })
<div class="valid-feedback"><i class="fa fa-check">Süpersin</i></div>
<div class="invalid-feedback "><i class="fa fa-times"></i></div>
</div>
</div>
<div class="form-group row">
#Html.LabelFor(model => model.CreatedDate, new { #class = "form-control-label col-md-3"})
<div class="col-md-9">
#Html.EditorFor(model => model.CreatedDate, "{0:yyyy-MM-dd}", new { htmlAttributes = new { #class = "form-control", type = "date", #readonly = "readonly",required="false" } })
</div>
</div>
<div class="form-group row ">
<label class="col-sm-3 col-form-label">Options</label>
<div class="col-sm-9 input-group">
<input type="text" class="form-control" name="option[]" required placeholder="Seçenek giriniz" />
<div class="input-group-append">
<button type="button" class="btn btn-success addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
</div>
<!-- The option field template containing an option field and a Remove button -->
<div class="form-group d-none row" id="optionTemplate">
<div class="offset-sm-3 col-sm-9 input-group">
<input class="form-control" type="text" name="option[]" required placeholder="Diğer seçenek giriniz." />
<div class="input-group-append">
<button type="button" class="btn btn-danger removeButton"><i class="fa fa-times"></i></button>
</div>
</div>
</div>
<div class="form-group row">
<input type="button" value="Submit" class="btn btn-primary" id="btnSubmit" />
<input type="reset" value="Reset" class="btn btn-secondary" />
</div>
}
<script>
$(document).ready(function () {
// The maximum number of options
var MAX_OPTIONS = 5;
$('#questionForm').on('click', '.addButton', function () {
var $template = $('#optionTemplate'),
$clone = $template
.clone()
.removeClass('d-none')
.removeAttr('id')
.insertBefore($template),
$option = $clone.find('[name="option[]"]');
// Add new field
$('#questionForm').bootstrapValidator('addField', $option);
})
// Remove button click handler
.on('click', '.removeButton', function () {
var $row = $(this).parents('.form-group'),
$option = $row.find('[name="option[]"]');
// Remove element containing the option
$row.remove();
// Remove field
$('#questionForm').bootstrapValidator('removeField', $option);
})
// Called after adding new field
.on('added.field.bv', function (e, data) {
// data.field --> The field name
// data.element --> The new field element
// data.options --> The new field options
if (data.field === 'option[]') {
if ($('#questionForm').find(':visible[name="option[]"]').length >= MAX_OPTIONS) {
$('#questionForm').find('.addButton').attr('disabled', 'disabled');
}
}
})
// Called after removing the field
.on('removed.field.bv', function (e, data) {
if (data.field === 'option[]') {
if ($('#questionForm').find(':visible[name="option[]"]').length < MAX_OPTIONS) {
$('#questionForm').find('.addButton').removeAttr('disabled');
}
}
});
});
$("#btnSubmit").click(function (event) {
var form = $("#questionForm");
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.addClass('was-validated');
SubmitForm(form);
});
</script>

Asp.net Ajax MVC login redirect to home not working

I am new on asp.net mvc and i am trying to redirect home controller after login.ajax is not redirecting to home page.below is my code
My login Page
#using (Html.BeginForm("Authorize", "Login", FormMethod.Post, new { id = "loginform", #class="form-horizontal form-material", onSubmit = "return doLogin(this);", data_restUrl = Url.Action("index", "Home", new { id = 0 }) }))
{
#Html.AntiForgeryToken()
<a href="javascript:void(0)" class="text-center db">
<img src="~/Scripts/plugins/images/eliteadmin-logo-dark.png" alt="Home" />
<br /><img src="~/Scripts/plugins/images/eliteadmin-text-dark.png" alt="Home" />
</a>
<div class="form-group m-t-40">
<div class="col-xs-12">
<input class="form-control" type="text" required="" name="UserKey" id="UserKey" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" name="UserPassword" id="UserPassword" required="" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="checkbox checkbox-primary pull-left p-t-0">
<input id="checkbox-signup" type="checkbox">
<label for="checkbox-signup"> Remember me </label>
</div>
<i class="fa fa-lock m-r-5"></i> Forgot pwd?
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light" type="submit">Log In</button>
</div>
</div>
}
Ajax Call
function doLogin(form) {
$.validator.unobtrusive.parse(form);
loader(true);
if ($(form).valid()) {
var ajaxConfig = {
type: 'POST',
url: form.action,
data: new FormData(form),
success: function (response) {
alert(response);
if (response.success) {
alert();
//$.notify(response.message, "success");
//window.location.href = $(form).attr('data-restUrl');
loader(false);
}
else {
alert("Something went wrong");
//$.notify(response.message, "error");
}
}
}
$.ajax(ajaxConfig);
}
return false;
}
My Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
My Login Controller
[HttpPost]
public JsonResult Authorize(User loginModel) {
try
{
using (POSEntities1 db = new POSEntities1())
{
User usr = db.Users.Where(x => x.UserKey == loginModel.UserKey && x.UserPassword == loginModel.UserPassword).FirstOrDefault<User>();
if (usr != null)
{
Session["UserID"] = usr.UserID;
Session["UserName"] = usr.UserFirstName +" " + usr.UserLastName;
return Json(new { success = true, message = "Login Sucessfully" }, JsonRequestBehavior.AllowGet);
}
else {
return Json(new { success = false, message = "In-valid Username or Password" }, JsonRequestBehavior.AllowGet);
}
}
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
When i click the login button and i am getting below response and ajax call back is not receiving,please guide me whats wrong with my code?
Error link
Could you please do the below changes.
1) On the form
onSubmit = "return doLogin(event);"
2)Add below code to your doLogin(event) method as the first line:
event.preventDefault();
In your Html.BeginForm change the data attribute from data_restUrl to data-restUrl.
Notice here hyphen (-) not an underscore (_).
And in you're ajax success response unhide the below line
window.location.href = $(form).attr('data-restUrl');
if you use newer jQuery >= 1.4.3:
window.location.href = $(form).data("restUrl");//instead of "data-restUrl", we can use "restUrl"
I did some changes on my code which is below there are two changes.
function doLogin(event, form)
{
event.preventDefault();
loader(true);
var ajaxConfig = {
type: 'POST',
url: form.action,
data: new FormData(form),
cache: false,
processData: false,
contentType: false,
success: function (response) {
if (response.success) {
window.location.href = $(form).attr('data-restUrl');
loader(false);
}
else {
alert("Something went wrong");
}
}
}
$.ajax(ajaxConfig);
return false;
}

Data is not getting posted from $.ajax to .Net core asp.net mvc method

Here is my server side method (which is getting data through postman)
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public HttpStatusCode RegisterNewUser(UserModel user)
{
return HttpStatusCode.OK;
}
}
Here is .jsx Code of javascript :
$.ajax({
url: "Home/RegisterNewUser",
type: "POST",
data: JSON.stringify(this.state),
dataType: "json",
contentType: "application/json",
success: function (status) {
console.log(status);
if (status == '200') {
alert('You are registered now !!');
this.setState({ Email: '', FirstName: '', LastName: '', LastNamePrefix: '', AcceptTerms: false, CompanyName: '' });
}
else {
alert(' you are not registered !!');
}
$('#forgetEmailId').val('');
$('#divGetPass').css('display', 'none');
$('#getPass').val('Send My Password on Email');
},
error: function () {
alert('Some error occured !!');
}
});
THis javascript code is hitting the debug pointer inside my server side method but the Model is not getting populated , while If I am hitting it using Postman then the Model is populated.
Here is full react code
var RegistrationBox = React.createClass({
getInitialState: function () {
return {Email:'', FirstName: '', LastName: '',LastNamePrefix:'',AcceptTerms:false,CompanyName:'' };
},
handleEmailChange: function (e) {
this.setState({Email: e.target.value });
},
handleFirstNameChange: function (e) {
this.setState({ FirstName: e.target.value });
},
handleLastNamePrefixChange: function (e) {
this.setState({ LastNamePrefix: e.target.value });
},
handleLastNameChange: function (e) {
this.setState({ LastName: e.target.value });
},
handleCompanyNameChange: function (e) {
this.setState({ CompanyName: e.target.value });
},
handleAcceptChange: function (e) {
this.setState({ AcceptTerms: e.target.checked });
},
toggleIsChecked: function () {
this.setState({ AcceptTerms: !this.state.checked });
},
handleReset: function (e) {
this.setState({ Email:'', FirstName: '', LastName: '', LastNamePrefix: '', AcceptTerms: false, CompanyName: '' });
},
handleSubmit: function (e) {
e.preventDefault();
var email = this.state.Email.trim();
var fName = this.state.FirstName.trim();
var lName = this.state.LastName.trim();
var lNamePrefix = this.state.LastNamePrefix.trim();
var cName = this.state.CompanyName.trim();
var aTerms = this.state.AcceptTerms;
if (email == null || fName == null || lName == null ||
lNamePrefix == null || cName == null || aTerms == null) {
return;
}
if (aTerms == false){
alert('Please accept Terms');
return;
}
else //Make Ajax Call
{
$.ajax({
url: "Home/RegisterNewUser",
type: "POST",
data: JSON.stringify(this.state),
dataType: "json",
contentType: "application/json",
success: function (status) {
console.log(status);
if (status == '200') {
alert('You are registered now !!');
this.setState({ Email: '', FirstName: '', LastName: '', LastNamePrefix: '', AcceptTerms: false, CompanyName: '' });
}
else {
alert(' you are not registered !!');
}
$('#forgetEmailId').val('');
$('#divGetPass').css('display', 'none');
$('#getPass').val('Send My Password on Email');
},
error: function () {
alert('Some error occured !!');
}
});
}
},
render: function () {
var chkBoxStyle = {
width: 25,
height: 25,
};
var chkboxlabel = {
margin: 8
};
return (
<div className="registrationBox">
<form method="post" id="user-registration-form" data-parsley-validate className="form-horizontal form-label-left">
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12">
Email <span className="required">*</span>
</label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input onChange={this.handleEmailChange} value={this.state.Email} type="text" id="email" required="required" className="form-control col-md-7 col-xs-12" />
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12">
First Name <span className="required">*</span>
</label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input onChange={this.handleFirstNameChange} value={this.state.FirstName} type="text" id="first-name" required="required" className="form-control col-md-7 col-xs-12" />
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12">
Last Name Prefix<span className="required">*</span>
</label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input onChange={this.handleLastNamePrefixChange} value={this.state.LastNamePrefix} type="text" id="last-name-prefix" name="last-name-prefix" required="required" className="form-control col-md-7 col-xs-12" />
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12">
Last Name <span className="required">*</span>
</label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input onChange={this.handleLastNameChange} value={this.state.LastName} type="text" id="last-name" name="last-name" required="required" className="form-control col-md-7 col-xs-12" />
</div>
</div>
<div className="form-group">
<label
style={chkboxlabel}
className="control-label col-md-3 col-sm-3 col-xs-12">
Accept Terms & Conditions
<span className="required">*</span>
</label>
<div className="checkbox col-md-6 col-sm-6 col-xs-12">
<div style={{ float: 'left', width: 60, paddingLeft: 5 }}>
<input onChange={this.handleAcceptChange} checked={this.state.AcceptTerms} type="checkbox" id="accept"
name="accept" required="required" style={chkBoxStyle} />
</div>
</div>
</div>
<div className="form-group">
<label className="control-label col-md-3 col-sm-3 col-xs-12">
Company Name <span className="required">*</span>
</label>
<div className="col-md-6 col-sm-6 col-xs-12">
<input onChange={this.handleCompanyNameChange} value={this.state.CompanyName} type="text" id="company-name" name="compnay-name" required="required" className="form-control col-md-7 col-xs-12" />
</div>
</div>
<div className="form-group">
<div className="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button className="btn btn-primary" type="button">Cancel</button>
<button onClick={this.handleReset} className="btn btn-primary" type="reset">Reset</button>
<button onClick={this.handleSubmit} type="button" className="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
);
}
});
ReactDOM.render(
<RegistrationBox />,
document.getElementById('registration-div')
);
this line
JSON.stringify(this.state)
is giving everything as expected.
Looks like I missed something really small but important.. :(
User Model
**
public class UserModel
{
public string Email { get; set; }
public string FirstName { get; set; }
public string LastNamePrefix { get; set; }
public string LastName { get; set; }
public bool AcceptTerms { get; set; }
public string CompanyName { get; set; }
}
**
while using Postman such POST request is working fine with same serverside code

Fill DropDownList Value from Database using Knockout

I'm using jQuery Ajax to load the data from the server and then bind it using Knockout JS, but the values do not display in DropDownList.
Here is the code:
View: Edit.cshtml
...
<div class="tab-content">
...
<div class="tab-pane" id="pnlLiquidation">
#{ Html.RenderPartial("~/Views/Liquidation/_Liquidation.cshtml", Model.LiquidationVM); }
</div>
</div>
...
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/knockout")
<script>
...
var companyID = #Html.Raw(ViewBag.CompanyID);
...
</script>
...
<script src="~/Scripts/LiquidationSystem/account-statement.js"></script>
...
}
View: _Liquidation.cshtml
...
<div class="tab-content">
...
<div class="tab-pane" id="pnlStage2Steps28_29">
#{ Html.RenderPartial("~/Views/Liquidation/_Stage2Steps28_29.cshtml", Model); }
</div>
...
</div>
View: _Stage2Steps28_29.cshtml
...
<div class="panel panel-primary">
<div class="panel-body" id="pnlAccountStatement">
#{ Html.RenderPartial("~/Views/AccountStatement/_AccountStatement.cshtml"); }
</div>
</div>
...
View: _AccountStatement.cshtml
<div class="row">
<div class="col-md-12">
Add New Statement of Accounts
<div class="form-horizontal" id="pnlAddEditAccountStatement">
<div data-bind="if: AccountStatement">
<h4>Update Statement of Account</h4>
...
</div>
<div data-bind="ifnot: AccountStatement()">
<h4>Add New Statement of Account</h4>
<div class="form-group">
<label class="control-label col-md-2">Type:</label>
<div class="col-md-10">
<select class="form-control"
data-bind="options: Types, optionsValue: 'Value', optionsText: 'Text', optionsCaption: '-- Please Select --', value: Type"></select>
</div>
</div>
<div class="form-group">
<input type="hidden" data-bind="value: $root.CompanyID" />
<label class="control-label col-md-2">Description:</label>
<div class="col-md-10">
<input type="text" placeholder="Enter Description" class="form-control"
data-bind="value: $root.Description" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Amount:</label>
<div class="col-md-4">
<input type="text" placeholder="Enter Amount" class="form-control"
data-bind="value: $root.Amount" />
</div>
<label class="control-label col-md-2">Receipt Date:</label>
<div class="col-md-4">
<input type="text" placeholder="Enter Receipt Date" class="form-control fdatepicker" readonly="readonly"
data-bind="value: $root.ReceiptDate" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
Save
Reset
Cancel
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h4>
<i>
<u>List of Statement of Accounts</u>
</i>
</h4>
...
</div>
</div>
Javascript: account-statement.js
function AccountStatementViewModel(companyID) {
var self = this;
self.AccountStatementID = ko.observable();
self.CompanyID = ko.observable(companyID);
self.Description = ko.observable();
self.Amount = ko.observable();
self.ReceiptDate = ko.observable();
self.Type = ko.observable();
var AccountStatement = {
AccountStatementID: self.AccountStatementID,
CompanyID: self.CompanyID,
Description: self.Description,
Amount: self.Amount,
ReceiptDate: self.ReceiptDate,
Type: self.Type
}
self.AccountStatement = ko.observable();
self.AccountStatements = ko.observableArray();
$.ajax({
url: webroot + 'AccountStatement/GetAccountStatements',
contentType: 'application/json; charset=utf-8',
data: { id: self.CompanyID },
cache: false
}).done(function (data) {
self.AccountStatements(data);
});
var clearInput = function () { ... }
self.create = function () { ... }
self.reset = function () { ... }
self.edit = function (accountStatement) { ... }
self.update = function () { ... }
self.cancel = function () { ... }
self.delete = function (accountStatement) { ... }
}
var accountStatementVM = new AccountStatementViewModel(companyID);
ko.applyBindings(accountStatementVM, document.getElementById('pnlAccountStatement'));
var Types;
$(function () {
$('#pnlAddEditAccountStatement').hide();
$('#lnkAddAccountStatement').click(function (e) {
e.preventDefault();
$('#pnlAddEditAccountStatement').show('blind', 1000);
$(this).hide('blind', 1000);
});
$.ajax({
url: webroot + 'AccountStatement/GetTypes',
contentType: 'application/json; charset=utf-8',
async: false,
cache: false,
dataType: 'json'
}).done(function (data) {
console.log('data = ' + data);
Types = data;
console.log('Types[0].Text = ' + Types[0].Type);
console.log('Types[0].Value = ' + Types[0].Description);
console.log('Types[1].Text = ' + Types[1].Type);
console.log('Types[1].Value = ' + Types[1].Description);
});
});
When I see the console:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
data = [object Object],[object Object]
account-statement.js:151 Types[0].Text = Receipts
account-statement.js:152 Types[0].Value = Receipts
account-statement.js:153 Types[1].Text = Payment
account-statement.js:154 Types[1].Value = Payment
Controller: AccountStatementController.cs
public JsonResult GetTypes()
{
List<SelectListItem> types = new List<SelectListItem>
{
new SelectListItem
{
Text = "Receipts",
Value = "Receipts"
},
new SelectListItem
{
Text = "Payment",
Value = "Payment"
}
};
}
Can I use SelectListItem rather than create the View Model? I've tried to create AccountStatementTypeViewModel.cs and replace the SelectListItem.
AccountStatementTypeViewModel.cs
public class AccountStatementTypeViewModel
{
public string Type { get; set; }
public string Description { get; set; }
}
update the GetTypes() method
public JsonResult GetTypes()
{
List<AccountStatementTypeViewModel> types = new List<AccountStatementTypeViewModel>
{
new AccountStatementTypeViewModel
{
Type = "Receipts",
Description = "Receipts"
},
new AccountStatementTypeViewModel
{
Type = "Payment",
Description = "Payment"
}
};
return Json(types, JsonRequestBehavior.AllowGet);
}
update the select tag in _AccountStatement.cshtml
<select class="form-control"
data-bind="options: Types, optionsValue: 'Type', optionsText: 'Description', value: Type"></select>
but the result is same, it cannot bind into the DropDownList value.
I've followed the code from this site and download the source code and see the code how do they fill the Phone Type dropdownlist. The tutorial use ASP.NET MVC 4, jQuery 1.8.3, and Knockout 2.2.0, but mine using ASP.NET MVC 5, jQuery 2.1.4, and Knockout 3.3.0. Is there any problem with the version differences?

Submit form with jquery ajax

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

Categories

Resources