I'm working on an MVC project.I have a form Like below:
<div id="horizontal-form">
#using (Html.BeginForm("Send", "Ticket", FormMethod.Post, new
{
#class = "form-horizontal",
role = "form",
id = "form_send_ticket",
enctype = "multipart/form-data"
}))
{
#**** I have about 20 filed's of other types here ****#
......
#**** Image file ****#
#Html.TextBoxFor(x => x.Image, new { type = "file" })
<div>
<button type="button" class="btn btn-success" id="send_ticket">Insert</button>
</div>
}
</div>
My ViewModel:
public class SendViewModel
{
//I have about 20 filed's of other types here
.....
//Image file
public HttpPostedFileBase Image { get; set; }
}
My JQuery ajax:
$("#send_ticket").click(function () {
var form = $("#form_send_ticket");
$.ajax({
type: "POST",
url: '#Url.Action("Send", "Ticket")',
data: form.serialize(),
contentType: "multipart/form-data",
success: function (data) {
//do something
},
error: function (e) {
//do something
}
});
})
My Controller Action is like this:
[HttpPost]
public ActionResult Send(SendViewModel ticket)
{
//Do something
return Json(new { });
}
Before this situation I faced,I mean in other projects,mostly I had about 3 to 8 field's including image file an some other types and I append them one by one to FormData(because of that Image file) then send them through ajax request and it was no matter for me,but now I have about 22 field's and it's a little though to do this.so I decided to serialize the form and send it through ajax request and it's working good form all filed's except Image which I make it the type HttpPostedFileBase in ViewModel. Any Idea how to send this field with form using data: form.serialize()?
appreciate your help :)
Update:
let me clear some point's:
1-I don't want FormData to send through ajax and I want to send using form.serialize().
2-Don't want to use ready file plugins.
3-I don't mean just one image field ,I mean whole the form with 23 field's.
You cannot post/upload a file using jQuery Ajax, unless you are going to use FormData or some plugins which internally use iFrame implementations.
Related
I am using ASP.NET Core 3.1 MVC to create a page with a form. The form has a dropdown and a textbox. The dropdown is populated with values from the database. The textbox will populate with a value from the same table and the dropdown, based on the selected dropdown value. My goal is to call a function from my controller inside of my view, is that possible?
My cshtml file:
<form method="post" asp-controller="Index" asp-action="Index" role="form">
<div class="form-group">
<select id="fileName" asp-items="#(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile()"></select>
<input />
</div>
</form>
My Model
public class myFiles
{
public int ID {get; set;}
public string fileName {get; set;}
public string uploadedFile {get; set;}
}
My controller has a function named GetUploadedFile() which runs a query to the database that returns the file name based on the ID. I originally thought I could reference the GetUploadedFile through my view(cshtml file) by adding the onchange handler and setting it as onchange="GetUploadedFile()". I have also tried to do an ajax call to get the UploadedFile.
My goal is to call a function from my controller inside of my view, is that possible?
Do you mean you want to add the myfiles' uploadfile value according to the dropdownlist selected value in the onchange getUploadedFile jquery method? If this is your requirement, I suggest you could try to use ajax to achieve your requirement.
You could write the ajax to post request to the mvc action, then you could get the value and set the result to the textbox.
Details, you could refer to below codes:
<form method="post" asp-controller="home" asp-action="Index" role="form">
<div class="form-group">
<input id="uploadedFile" type="text" class="form-control" />
<select id="fileName" asp-items="#(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile(this)"></select>
</div>
</form>
<script>
function getUploadedFile(Sle) {
$.ajax({
url: "/Home/GetUploadfileName",
data: { "FileID": Sle.value} ,
type: "Post",
dataType: "text",
success: function (data) {
console.log(data);
$("#uploadedFile").val(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
Action method:
private List<myFiles> myfiletestdata = new List<myFiles>() {
new myFiles(){ ID=1, fileName="test1", uploadedFile="testuploadfile" },
new myFiles(){ ID=2, fileName="test2", uploadedFile="testuploadfile2" },
new myFiles(){ ID=3, fileName="test3", uploadedFile="testuploadfile3" },
};
[HttpPost]
public IActionResult GetUploadfileName(int FileID) {
//get the filename result accoding to ID
var result = myfiletestdata.Where(x=>x.ID== FileID).First();
return Ok(result.uploadedFile);
}
Result:
If I understand correctly, you just want to get the file name from the database when a value from the dropdown is selected.
What errors did you get when you tried the ajax call??
In your cshtml file, you can have something like this:
<script>
function getUploadedFile() {
var id = $('#fileName option:selected').val();
$.getJSON('/ControllerName/GetUploadedFile', { id: id }, function (result) {
var file = result.fileName;
.... do whatever with the result
to set value of the textbox:
$('#textBoxId').text(file);
});
}
</script>
Instead of getJSON, you could use ajax:
<script>
function getUploadedFile() {
var id = $('#fileName option:selected').val();
$.ajax({
url: 'ControllerName/GetUploadedFile',
type: 'GET',
dataType: 'json',
data: {
'id': id
}
})
.done(function (result) {
if (!result.errored) {
var file = result.fileName;
}
else {
}
});
}
</script>
Then in your controller, if you are not submitting the form and just want to update the value of the textbox, then it can just be:
[HttpGet]
public async Task<IActionResult> GetUploadedFile(int id)
{
Sample code:
var file = await GetFileFromDb(id);
return Json(new { fileName = file });
}
Also, you should consider using ViewModels instead of ViewBag.
I am trying to validate a submitted form that is loaded in isolation to the rest of the page. I use validation all the time with my normal non ajax loaded content. I go on this principle:
Submit the form
pass the request from my controller to my service
Validate the object in the service
pass back to the controller a bool depending on the validation state
Present the original form back with validation summary if there are validation errors
Present a success page if there are no validation errors
That works fine on non-ajax content.
Now lets consider my issue. I have this kind of structure:
<div id="mainContent">
<div id="leftContent"></div>
<div id="rightContent"></div>
</div>
<script>
$.ajax({
url: baseUrl + "home/newApplicationForm/",
type: "GET",
success: function (data) {
$("#rightContent").html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error displaying content");
}
});
</script>
This puts my blank application form on the right hand side of the page.. everything else on the page is left unchanged by that ajax.
So home/newapplicationform now displays the form that is wrapped with:
#model homelessRentals.Model.Application
#{
AjaxOptions options = new AjaxOptions{
HttpMethod = "Post",
UpdateTargetId = "AddApplication"
};
}
#using (Ajax.BeginForm(options)) {
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.EditorFor(model => model.YourName)
#Html.ValidationMessageFor(model => model.YourName)
</div>
<input type="submit" value="Add Application" id="saveMe"/>
}
This form now pings back to my controller:
[HttpPost]
public ActionResult AddApplication(Application app)
{
bool validated = _service.AddApplication(app);
if(validated)
{
return PartialView("SuccessApp");
}
return PartialView(app);
}
This will either return me to my form with validation errors shown or route me to my success page. This works to the extent that the logic is right, BUT I get presented the partial view in replacement of the whole page - it is not presented back in the 'rightContent' div.
I have tried submitting the form and catching the submission in jquery, then running something like this but I get the same behaviour:
$.ajax({
url: baseUrl + "home/AddApplication/",
data: "{'app':" + JSON.stringify(newApp) + "}",
type: "POST",
success: function (data) {
$("#rightContent").html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error displaying content");
}
});
Can anyone help me with a better way to achieve this validation?
Many thanks
The UpdateTargetId is incorrect, this needs to point to rightContent rather than AddApplication.
#{
AjaxOptions options = new AjaxOptions{
HttpMethod = "Post",
UpdateTargetId = "rightContent"
};
There is no dom element with the id of AddApplication.
I need to pass data from View to Controller(From TestView1 to TestController2)
#Html.ActionLink("Text", "Index", "Sample", new { testId = test }, null)
Currently this is sending Data in QueryString. But i need to avoid this and pass data to Controller without Query string ?
How do i achieve without Querystring ?
I searched and most of them were by using Query string. If i missed out on solutions please redirect to correct path.
Thanks
Have you tried to post your data to the controller, if possible? Keeping a form and hidden fields..
e.g http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
You can send data using Ajax call back. try this method on your link/button
#* Your button/link *#
<input type="button" onclick='Link1()'" value="Submit" />
<script type="text/javascript">
function Link1() {
var Id = $("#txt").val();
$.ajax({
url: '#Url.Content("~/Test2/Actionname")',
type: 'post',
async: true,
data: { text: Id },
success: function (data) {
alert("Success");//Ajax request success
alert(data);//data from Test/yourAction
},
error: function (err) {
alert("fail");//Ajax request fail
alert(err.responseText);//error will displayed here
}
});
}
</script>
I am trying to create a sample MVC4 webpage with partialViews
on my parent page ,eg., Index.cshtml page I am displaying a partialView page which will allow the user to view/update profile photo
When the index page loads ,I need this partial page to show up the photo if photo is available
once the page is loaded ,when the user uploads a new photo,I need only the partialView page to do an ajax postback and show up the new photo .
I am able to load the page with photo fetched from DB,
I am able to Save new photo to db by clicking "#btnPhotoUpload" button.
But after saving the photo ,the partialview is not getting refreshed automatically.Please help me how to get my partialview page to refesh and display the updated photo.
Here is my index page ie., "Index.cshtml"
#model MvcSamples.Models.ViewModels.UserInfoViewModel
#{
ViewBag.Title = "Ajax Partial Postback demo";
ViewBag.UserId = 1;
}
<h2>PersonalInfo example</h2>
<div id="photoForm">
#Html.Partial("_UserPhoto")
</div>
<div id="OtherDetails">
#Html.Partial("_UserDetails")
</div>
Here is my PartialView, i.e. _UserPhoto.cshtml
#model MvcSamples.Models.ViewModels.UserInfoViewModel
#using (Ajax.BeginForm("SaveProfilePhoto", "Example", new { id = "1" }, new AjaxOptions { UpdateTargetId = "photoForm", OnSuccess = "onSuccess" }, new { encType = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<a>
<img id="imgPhoto" width="100px" height="100px"/>
<label for="photo">Photo:</label>
<input type="file" name="photo" id="photo" />
<input id="btnPhotoUpload" type="button" value="Apply" />
</a>
<script type="text/javascript">
$(document).ready(function () {
$("#imgPhoto").attr('src', "#Url.Action("GetProfileImage", "Example", new { id = ViewBag.UserId })");
$("#btnPhotoUpload").click(function (event) {
//on-click code goes in here.
event.preventDefault();
SavePhotoToDb();
});
function SavePhotoToDb() {
var json;
var data;
$.ajax({
type: "POST",
url: "/Example/SaveProfilePhoto",
data: new FormData($("#form0").get(0)),
dataType: "html",
contentType: false,
processData: false,
success: saveItemCompleted(data),
error: saveItemFailed
});
}
function saveItemCompleted(data) {
$("#photoForm").html(data);
}
function saveItemFailed(request, status, error) {
}
});
</script>
}
Here is my controller ExampleController:
namespace MvcSamples.Controllers
{
public class ExampleController : Controller
{
IUserDetails usr = new UserDetails();
// GET: /Example/
[HttpGet]
public ActionResult Index()
{
//usr.GetProfilePhoto(WebSecurity.GetUserId(User.Identity.Name));
if (!string.IsNullOrWhiteSpace(User.Identity.Name))
{
ViewBag.UserId = WebSecurity.GetUserId(User.Identity.Name);
}
UserInfoViewModel model = new UserInfoViewModel();
model.GenderList = usr.FillGenderTypesDropDownList();
return View(model);
}
[HttpPost]
public ActionResult SaveProfilePhoto(HttpPostedFileBase photo, UserInfoViewModel model)
{
string path = #"C:\Temp\";
if (photo != null)
{
model.UserId = 1;//WebSecurity.GetUserId(User.Identity.Name);
ViewBag.UserId = model.UserId;
var binary = new byte[photo.ContentLength];
photo.InputStream.Read(binary, 0, photo.ContentLength);
UserPicModel upModel = new UserPicModel();
upModel.UserPhoto = binary;
upModel.UserId = model.UserId;
usr.InsertProfilePhoto(upModel);
}
return PartialView("_UserPhoto", model);
}
public FileResult GetProfileImage(int id)
{
byte[] barrImg = usr.GetProfilePhoto(id);
return File(barrImg, "image/png");
}
}
}
Update:
As #David Tansey suggested ,I added code to refresh image inside SaveCompleted(data).
function RefreshImage() {
$("#imgPhoto").attr('src', function () {
// the datetime portion appended to the url avoids caching issues
// and ensures that a fresh image will be loaded every time
var d = new Date();
return this.src + '?' + d.getTime();
});
}
But the above code is refreshing the image only after I click the upload button twice .
Actually I need this to refresh the image immediately after the $("#btnPhotoUpload").click. Any suggestions?
I also tried disabling cache at the controller but no luck:
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
I am pretty sure the problem is that the browser is caching the image file and does not 'perceive' the need to bring it across the wire again after you upload a new one.
Look at the following post for a description of how to attach a dummy (yet dynamic) query string value to prevent the caching from occuring. I think this approach will solve your problem.
asp.net mvc jquery filling image
Hope that helps.
I'm using Html.Beginform in view page and get the parameters using FormCollection to the controller i want to return the Success message on the same ViewPage as a result.i'm using following code,
public string InsertDetails(FormCollection collection)
{
string result = "Record Inserted Successfully!";
return result;
}
It shows the success message on the new page.How can i resolve this? what i have to return to get the Success message on the same page?
Personally, I'd pop the result string into the ViewBag.
public ActionResult InsertDetails(FormCollection collection)
{
//DO LOGIC TO INSERT DETAILS
ViewBag.result = "Record Inserted Successfully!";
return View();
}
Then on the web page:
<p>#ViewBag.result</p>
I have following Options.
1. Use Ajax Begin Form with AjaxOptions like below
#using (Ajax.BeginForm("ActionName", "ControllerName", new { area = "AreaName" }, new
AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "alert('Success');" //This will execute once the Ajax call is finished.
}, null))
{
<input type="submit" name="nameSubmit" value="Submit" />
}
2. Use JQuery to Manually Setup the XHR Request
$.ajax({
url: "#Url.Action("ActionName", "ControllerName", new { area = "AreaName" });",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({param : Value})
})
.done(function () { alert('Success');}) //This will execute when you request is completed.
.fail(function () { })
My Suggestions
There are following disadvantages while using the FormCollection
Point - 1
In case FormCollection is being used...It will be mandatory to Type Cast the Primitive Type Values un-necessarily because while getting the entry of specific Index of the System.Collections.Specialized.NameValueCollection, value being returned is of type String. This situation will not come in case of Strongly Typed View-Models.
Issue - 2
When you submit the form and goes to Post Action Method, and View-Model as Parameter exists in the Action method, you have the provision to send back the Posted Values to you View. Otherwise, write the code again to send back via TempData/ViewData/ViewBag
Point - 3
We have Data Annotations that can be implemented in View Model or Custom Validations.
ASP.Net MVC simplifies model validatons using Data Annotation. Data Annotations are attributes thyat are applied over properties. We can create custom validation Attribute by inheriting the built-in Validation Attribute class.
Point - 4
Example you have the following HTML
<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" />
Question : How can we access the value of customAttr1 from the above eg from inside the controller
Answer : When a form get posted only the name and value of elements are posted back to the server. You can also use Hidden Fields to post the Attributes to Post Action method.
Alternatives : Use a bit of jQuery to get the custom attribute values, and post that along with the form values to action method
Another option is to rather put what you got in your custom attributes in hidden controls
That's the reason, I would always prefer to use View-Models
we can do it on Form inside view
#using (Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "POST", OnSuccess = "Showmessage" }))
[HttpPost]
public ActionResult Test(TestViewModel model)
{
return Json(new {isok=true, message="Your Message" });
}
function Showmessage(data)
{
$('#Element').html('Successfully Submitted');
}