How do I pass a whole set model object through formdata and convert it to model type in the controller?
Below is what I've tried!
JavaScript part:
model = {
EventFromDate: fromDate,
EventToDate: toDate,
ImageUrl: imgUrl,
HotNewsDesc: $("#txthtDescription").val().trim(),
};
formdata.append("model",model);
then pass it through AJAX, it will be a string, and if I check the value of Request.Form["model"] the result will be same, that is it will be received as string and value will be "[object object]"
Is there any way to pass model through formdata and receive it in the controller?
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using
var formdata = new FormData($('form').get(0));
This will also include any files generated with <input type="file" name="myImage" .../>
and post it back using
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
and in your controller
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
formdata.append('someProperty', 'SomeValue');
If you want to send Form data using Ajax.This is the way to send
var formData = new FormData();
//File Upload
var totalFiles = document.getElementById("Iupload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Iupload").files[i];
formData.append("Document", file);
}
formData.append("NameCode", $('#SelecterID').val());
formData.append("AirLineCode", $('#SelecterID').val());
$.ajax({
url: "/Controller/ActionName",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
success: function (result) {
}
})
Using Pure Javascript, considering you have
<form id="FileUploadForm">
<input id="textInput" type="text" />
<input id="fileInput" type="file" name="fileInput" multiple>
<input type="submit" value="Upload file" />
</form>
JS
document.getElementById('FileUploadForm').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//text value
formdata.append("textvalue",document.getElementById("textInput").value);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/UploadFiles');
xhr.send(formdata); // se
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//on success alert response
alert(xhr.responseText);
}
}
return false;
}
in your C# controller you can get values it as below
[HttpPost]
public ActionResult UploadFiles(YourModelType model, HttpPostedFileBase fileInput)
{
//save data in db
}
Reference : File Uploading using jQuery Ajax or Javascript in MVC
In view side ,if you are using ajax then,
$('#button_Id').on('click', function(){
var Datas=JSON.stringify($('form').serialize());
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: '#Url.Action("ActionName","ControllerName")',
data:Datas,
cache: false,
dataType: 'JSON',
async: true,
success: function (data) {
},
});
});
In Controller side,
[HttpPost]
public ActionResult ActionName(ModelName modelObj)
{
//Some code here
}
Related
I am trying to display events in the dhtmlx scheduler and pass the clicked event id to another registration form (view). I can get the event_id but I have no clue how to pass the event_id to controller action. My sample code is below:
<h2>Appointment Calendar</h2>
#using (Html.BeginForm())
{
<div class="scheduler_container" style='height: 600px;'>
#Html.Raw(Model.Render())
</div>
}
<script>
scheduler.attachEvent("onClick", function (id, e) {
console.log(id);
//call controller method
$.ajax({
type: "POST",
url: "/Home/Registration",
data: { EventId: id },
// data: {EventId:$('#event_id').val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
window.location.href = "Registration/" + id;
},
error: function (response) {
}
});
//window.location.href = "Registration/" + id;
return true;
});
</script>
controller:
public ActionResult Registration(int? EventId) <- the EventId is null here
{
var Event = db.Appointments.Where(s => s.Id.Equals(EventId)).FirstOrDefault();
...
return View();
}
I have a view in ASP.NET MVC application, with a dropdownlist and other text fields. The dropdownlist is populated with file names from a specific directory. So, on selection of a specific file name from the dropdownlist, I want to populate other text fields with contents on the selected file. The reading of the file is already taken care of.
I'm struggling with filling in the text fields after file name selection from the dropdownlist.
How can I do this?
<div class="col-lg-4">
#Html.DropDownList("cardProgram", null, "--Select--", new { #class = "form-control input-group-lg" })
</div>
Ajax code:
$(document).ready(function () {
$("#FileDDL_ID").change(function () {
var file = $('#FileDDL_ID option:selected').text();
$.ajax({
url: "#Url.Action("YourAction", "Controller")",
type: "POST",
dataType: "json",
data: { filename: file }, //pass file as parameter to controller
async: false,
error: function () {
},
//assuming your data property is called fileDetail1
success: function (data) {
if (Object.keys(data).length > 0) {
$('#fileDetailtxtBox1').val(data[0].fileDetail1);
$('#fileDetailtxtBox2').val(data[0].fileDetail2);
}
}
});
});
});
Controller code:
[HttpPost]
public JsonResult YourAction(string filename)
{
using (var db = new DataContext())
{
//use filename as condition
var details = db.YourDbset.Condition.ToList();
return Json(details, JsonRequestBehavior.AllowGet);
}
}
Hope this is clear, I have tried to name variables as per your question. So basically, you are passing the selected value from the dropdown to the Controller action and getting back related data and populating fields with jQuery Ajax.
I finally got it working. See below :
html code:
#Html.LabelFor(m => m.cardProgram, new { #class = "col-lg-2" })
<div class="col-lg-4">
#Html.DropDownListFor(m => m.cardProgram, null, "--Select Card Profile--", new
{
#class = "col-lg-4 form-control input-group-lg",
#onchange = "BindProfile()"
})
</div>
ajax code:
<script>
function BindProfile() {
var selectedProfile = $('#cardProgram').val();
$.ajax({
url: '/CardCreation/BindProfile',
type: "GET",
dataType: "JSON",
data: { cardProgram: selectedProfile },
success: function (profile) {
$("#sBin").val(profile.card.bin)
$("#IsChip").val(profile.card.chip)
$("#IsBatches").val(profile.output.splitBatches)
$("#BatchSize").val(profile.output.batchSize)
$("#SplitPostcard").val(profile.output.splitPostcardFile)
$("#SubCat").val(profile.batchDetails.subcategory)
$("#UserCodeIncrement").val(profile.batchDetails.usercodeIncrement)
$("#ExpiryDate").val(profile.batchDetails.expiryWindowMM)
$("#Bureau").val(profile.chipDetails.bureau)
$("#BatchType").val(profile.chipDetails.batchType)
$("#EffectiveDate").val(profile.chipDetails.effectiveDateOffsetMM)
$("#ServiceCode").val(profile.emvApplications[0].serviceRestrictionCode)
}
});
}
</script>
Controller code:
public async Task<ActionResult> BindProfile(string cardProgram)
{
var profile = new Profile();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:59066/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ViewBag.country = "";
HttpResponseMessage response = await client.GetAsync(client.BaseAddress + "api/CardCreation/GetSelectedCardProfile?selectedProfile=" + cardProgram);
if (response.IsSuccessStatusCode)
{
//profile = response.Content.ReadAsAsync<Profile>().Result;
profile = JsonConvert.DeserializeObject<Profile>(response.Content.ReadAsStringAsync().Result);
return Json(profile, JsonRequestBehavior.AllowGet);
}
else
{
return Json(profile, JsonRequestBehavior.AllowGet); ;
}
}
}
I am a beginer ...I don't know how to use dropdown in MVC this....I have used it like this
In ItemMaster.cshtml
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
In Controller.cs
public ActionResult ItemMaster(Item model)
{
ObservableCollection<Item> ItemList = new ObservableCollection<Item>();
Item Item = new Models.Item();
ItemList = Item.GetItemList();
Item Product = new Item();
DataTable dtProduct = new DataTable();
dtProduct = Item.GetProductList();
IList<Item> MyList = new List<Item>();
foreach (DataRow mydataRow in dtProduct.Rows)
{
MyList.Add(new Item()
{
Id = Convert.ToInt32(mydataRow["Id"].ToString().Trim()),
Product_Name = mydataRow["Name"].ToString().Trim()
});
}
var ProductName = new SelectList(MyList, "Id", "Product_Name");
ViewData["ProductName"] = ProductName;
return View(ItemList);
}
I am using Item list to fill grid view.... And I am using view data to fill drop down list....It is working fine.... I don't know how to get selected value when Button is clicked.
Try this,
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
<input type="button" id="btnasd" value="Click"/>
Script
<script type="text/javascript">
$(document).ready(function () {
$("#btnasd").click(function () {
var Id = $("#ProductName").val();
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: "Post",
data: { ProductNameId: Id },
success: function (result) {
$("#mygrid").html('');
$("#mygrid").append(result.Data);
}
});
});
});
</script>
Do following(for onchange event of DropDownList):
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-", new { onchange = "doFunction();" })
javascript:
<script type="text/javascript">
$(document).ready(function () {
doFunction();
});
function doFunction() {
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
}
</script>
Or On button click
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-")
<input type="button" id="btnSubmit" value="Submit"/>
script:
$('#btnSubmit').click(function(){
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
});
Ask me if you have any query.
Note: You can also use DropDownListFor for model binded dropdown.
In my html I have
<h2>Title goes here</h2>
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "myFormID" })) {
<input type="text" id="testinput" name="testinput" />
<input type="text" id="testinput2" name="testinput2" />
<input type="button" value="click me" onclick="submitForm();" />
}
in my js I have
function submitForm() {
dataString = $("#myFormID").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "/Controller/Action",
data: dataString,
cache: false,
dataType: "json",
success: function (data) {
alert('success!');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + "<br />" + textStatus + "<br />" + errorThrown);
}
});
}
In my controller file I have:
public ActionResult Action()
{
return View();
}
[HttpPost]
public ActionResult Action(string testinput, string testinput2)
{
return View();
}
When clicked on "click me" button, I get the following error:
"parsererrorInvalid JSON: "
What am I doing wrong? I am simply trying to pass form data to jquery .ajax.
The alert statement outpust "testinput=gdfgf&testinput2=gfgfd" which is the correct values I entered. SO the error seems to be when serializing....
I am using MVC 3 with razor...I had the impression that passing data between model/view and javascript code was made easier.
I am almost positive that has nothing to do with the data you pass to the $.ajax call and everything with the data returned by /Controller/Action. Open up Fiddler and examine the response. it is likely malformed (or not JSON at all).
if your method accepts only int id as parameter, then dataString should be declared as
var dataString = { id: $("#myFormID").val() };
if you need to pass id and testinput as parameters, then use
var dataString = { id: $("#myFormID").val(), testinput: $("#testinput").val() };
The parameters and names in dataString mutch match the parameters of your action method.
Just wondering, how can I bind an image (stream) returned by an action method in an ajax call to an image element using jquery.
JavaScript:
$(document).ready($(function () {
$(':input').change(function () {
// object
var Person = {
Name: 'Scott',
Address: 'Redmond'
};
// Function for invoking the action method and binding the stream back
ShowImage(Person);
});
}));
function ShowImage(Person) {
$.ajax({
url: '/Person/GetPersonImage',
type: "Post",
data: JSON.stringify(Person),
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
// idImgPerson is the id of the image tag
$('#idImgPerson')
.attr("src", data);
},
error: function () {
alert('Error');
}
});
Action method:
public FileContentResult GetPersonImage(Person person)
{
// Get the image
byte[] myByte = SomeCompnent.GetPersonImage(person);
return File(myByte, "image/png");
}
Problem:
The Action method is returning the stream, but it is not getting rendered on the page.
I am I missing some thing here...
Thanks for looking in to it.
So I was working on this today and ran into your question, which helped (and hurt) me. Here is what I found:
Like Eben mentioned you cant have the json data type. but thats only part of the problem. When you try to $('#idImgPerson').attr("src", data); as in your code you will just set the src attribute to the bytes returned by the call do the GetPersonImage() method.
I ended up using a partial view:
Using the standard mvc3 template
Index.cshtml (excerpt):
<h3>Using jquery ajax with partial views</h3>
<div id="JqueryAjax">
<input class="myButton" data-url='#Url.Action("GetImagesPartial","Home")' name="Button1" type="button" value="button" />
Create the partial view which makes reference to the action that provides the image:
#model string
<div>
<img id="penguinsImgActionJquery" alt="Image Missing" width="100" height="100"
src="#Url.Action("GetPersonImage", "Home", new { someString=Model })" />
<br />
<label>#Model</label>
</div>
HomeController with both action methods:
public ActionResult GetImagesPartial(string someImageName)
{
return PartialView((object)someImageName);
}
public FileContentResult GetPersonImage(string someString)
{
var file = System.Web.HttpContext.Current.Server.MapPath(localImagesPath + "Penguins.jpg");
var finfo = new FileInfo(file);
byte[] myByte = Utilities.FileManagement.FileManager.GetByteArrayFromFile(finfo);
return File(myByte, "image/png");
}
Jquery:
$(document).ready(function () {
$('.myButton').click(function (e) {
var bleh = $(this).attr("data-url");
e.preventDefault();
someData.runAjaxGet(bleh);
});
var someData = {
someValue: "value",
counter: 1,
};
someData.runAjaxGet = function (url) {
_someData = this;
$.ajax({
url: url,
type: "Get",
data: { someImageName: "ImageFromJQueryAjaxName" + _someData.counter },
success: function (data) {
$('#JqueryAjax').append(data);
_someData.counter = _someData.counter + 1;
},
error: function (req, status) {
alert(req.readyState + " " + req.status + " " + req.responseText);
}
});
};
});
sorry I know there is a little bit of extra code in the script file i was trying to play with namespaces too. Anyhow, i guess the idea is you request the partial view with ajax, which contains the image rather than requesting the image directly.