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();
}
Related
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
}
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.
I am trying to call an action from jQuery. The action should return true or false,
and based on the return value I will do something.
I have the following code.
$("#payment").click(function (e) {
if($("#deliverytime").attr("disabled")){
//something here...
}
else
{
var postcode=$('#Postcode').val();
var restId='<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid="+restId+"&&postcode="+postcode;
$.ajax({
type: "GET",
url: URL
}).done(function(msg) {
if(msg==true){
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
else{
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
});
}
});
The code is not working. It says 'msg' is not defined. Is this not the way I should do this using jQuery-ajax? What am I doing wrong?
EDIT:
Controller action
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(Boolean.FalseString, JsonRequestBehavior.AllowGet);
}
else
return Json(Boolean.TrueString, JsonRequestBehavior.AllowGet);
}
Modified function
var postcode = $('#DeliveryInfo_Postcode').val();
var restId = '<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid=" + restId + "&&postcode=" + postcode;
$.ajax({
url: URL,
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
$('#commonMessage').html(data);
return false;
}
}
});
EDIT -2
<script>
$(document).ready(function () {
$("#checkout").click(function (e) {
getDeliveryInfo();
});
});
function getDeliveryInfo() {
var URL ="/Restaurant/DoesRestaurantDeliver/6/2259"
$.get(URL, function (data) {
alert(data.isValid);
});
}
</script>
<%using (Html.BeginForm())
{ %>
<input type="submit" name="submit" id="checkout"/>
<%} %>
The above code does not work. But If i put the 'checkout' button out side of the form like below, it works.
<%using (Html.BeginForm())
{ %>
<%} %>
<input type="submit" name="submit" id="checkout"/>
You can configure your ajax call like below.
I feel your ajax call having problems on .done(function(msg) {} area.
Try to set success: function (data) {} like below.
<script type="text/javascript">
$(function () {
var companyName = $("#companyname");
$.ajax({
url: "/Company/GetName",
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
companyName.html(data.companyName);
}
}
});
});
</script>
EDIT
Action method should looks like below (This is a sample.Adjust it according to your situation)
[HttpGet]
public JsonResult GetName(string term)
{
var result = Repository.GetName(term);
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT 2
I would use Anonymous object (isValid) (remember that JSON is a key/value pairs):
Action Method
[HttpGet]
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(new { isValid = false},JsonRequestBehavior.AllowGet);
}
else
return Json(new { isValid = true },JsonRequestBehavior.AllowGet);
}
And then inside the ajax method:
success: function(data) {
if (data.isValid) {
...
}
}
EDIT 3
Just change your button type as below.(since you're not sending any values from form)
<input type="button" name="submit" id="checkout"/>
I implemented a small test that is based on Scott Guthrie article
http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
But my controller action thinks that object passed to it is null, even though I used JSON.stringify on it and packed data to it - I followed the article exactly.
In my html
#using (Html.BeginForm("SomeAction", "ControllerName", FormMethod.Post, new { id = "FormID" })) {
<div class="editor-field">#Html.EditorFor(model => model.Date)</div>
<div class="editor-field">#Html.EditorFor(model => model.Id)</div>
<div class="editor-field">#Html.EditorFor(model => model.Name)</div>
<input type="button" value="save" onclick="Save();" />
}
In my model file
namespace MyNamespace.Models
{
public class MyModel
{
public string Id { get; set; }
public string DateReceived { get; set; }
public string Name { get; set; }
}
}
In my js
function Save() {
var myModelObj = { Id: $("#Id").val(),
DateReceived: $("#DateReceived").val(),
Name: $("#Name").val()
};
$.ajax({
type: "POST",
url: "/ControllerName/SomeAction",
data: JSON.stringify(myModelObj),
cache: false,
// dataType: "json",
success: function (data) {
alert('success!');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
alert(XMLHttpRequest + "<br />" + textStatus + "<br />" + errorThrown);
}
});
In my controller
[HttpPost]
public ActionResult SomeAction(MyModel modelObj )
{
using (StreamWriter sw = new StreamWriter("/test.txt") )
{
sw.Write(modelObj.Id);
}
return null;
}
When I put a break point on sw.Write...statement, modelObj.Id is null.
Am I missing something or is there anything else that needs to be wired up? Thanks!
I think you need to add the contentType and dataType options to your ajax call.
contentType: 'application/json, charset=utf-8',
dataType: 'json',
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.