MVC/Razor File Upload View - asp.net-mvc

I self admitted newbie, but I have a view with some code I pasted to provide a file upload. The function works but if the code is in, the "Save" button for the View that was already there stops working. If I had to guess it has something to do with the "HTML.BeginForm" line being there twice.
Here is the top of the view,
#model BrooksSOR.Models.dataOffender
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<div >
<h2>Upload Files in MVC</h2>
<img src="#Model.Photograph" width="250" height="250" />*
#using (Html.BeginForm("FileUpload", "SOR",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File"/>
<input type="hidden" name="parmPersonID" value="#Model.PersonID" />
}
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>dataOffender</legend>
<p>
<input type="submit" value="Save" />
<input id="Details" type="button" value="Details" />
</p>
</fieldset>

Remove the #html.BeginForm
The script you would need to send for a file and some other fields with it.
//Purpose: Form Submit: SAVE Client
document.getElementById('frmPage').onsubmit = function (e) {
debugger;
var file = document.getElementById('fileToUpload').files[0];
var filename;
if (file) {
filename = file.name;
}
else {
filename = "";
}
$('#Image').val(filename);
var formObj = $(this);
var formURL = '#Url.Action("SaveMethod", "ControllerName")';
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function (data, textStatus, jqXHR) {
debugger;
alert("Client saved successfully");
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
e.preventDefault(); //Prevent Default action.
}
This is the design:
<div>
<form id="frmPage" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label id="lblImage" class="col-md-3 control-label">Upload File</label>
<div class="col-md-4">
<input type="file" id="fileToUpload" name="file" />
</div>
</div>
<div class="modal-footer" style="margin-top: 0px">
<div class="pull-right">
<button type="submit" id="btnSave" class="btn blue Save">Save</button>
</div>
</div>
</form>
</div>
Here: The btnSave is submit type, so it will submit that particular form. and form named frmPage will do the jquery script we added.

Related

Viewbag content does not appear

I have an APS.Net web app Razor view where I attempt to display the Viewbag.errormessage.
The action method populates the viewbag but the view does not show the error message that is in the viewbag. It does not appear. Why?
The paragraph to which the Viewbag is attached to does not even appear per the 2nd pic. In the 1st pic, I can see that is there.
I also tried using 'TempData' but it produces the same result - not appearing.
Here is the action method (simplified):
[HttpPost]
public async Task<ActionResult> DeleteUserAccount(string userName, string
password)
{
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
ViewBag.errormessage = "The 'user name' or 'password' is
invalid - empty. Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
ViewBag.errormessage = "Your 'user name' is invalid. It
is not the same as the 'user name' used at original sign
in. Please try again.";
}
}
}
catch (Exception ex1)
{
}
return View();
}
Here is the view:
#Html.AntiForgeryToken()
<div class="login-panel">
#if (ViewBag.errormessage != null)
{
<p class="alert alert-danger" id="errorMessage">#ViewBag.errormessage</p>
}
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
$(".btn-yes4").click(function () {
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "User")',
data: { userName: holdUserName, password: holdPassword},
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
$("#myModal4").on('hidden.bs.modal', function () {
$("#myModal4").remove();
});
});
})
</script>
https://dotnetfiddle.net/U6HGHD
Ajax makes a call and does not re-render a page
Controller
[HttpPost]
//I made method snchronous as it has no await, and there are no resources to add await to
public ActionResult DeleteUserAccount(string userName, string password)
{
var errorMessage = String.Empty;
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
//since this method is ajax, the view will not re-render, so errors need
//to go into return value.
//ViewBag.errormessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
errorMessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
//ViewBag.errormessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
errorMessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
}
}
}
catch (Exception ex1){}
//return View();
//since this is ajax, I am returning a json
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
public ActionResult Index19()
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index19</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js" integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
//put this in here
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
//fixed the following line
});
$(".btn-yes4").click(function () {
//put these here
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "Home")',
data: { userName: holdUserName, password: holdPassword },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
if (data.length > 0) {
$("#errorMessage").css("display", "block");
}
else {
$("#errorMessage").css("display", "none");
}
$("#errorMessage").text(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
//$("#myModal4").on('hidden.bs.modal', function () {
// $("#myModal4").remove();
//});
});
</script>
</head>
<body>
#Html.AntiForgeryToken()
<div class="login-panel">
#*took out condition, and started with style none*#
#*#if (ViewBag.errormessage != null)
{*#
<p class="alert alert-danger" id="errorMessage" style="display:none">#ViewBag.errormessage</p>
#*}*#
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Get object from controller to view using ajax in .net mvc core

Controller:
[HttpGet]
public IActionResult Edit(int id)
{
Teacher teacher = teacherService.GetTeacherById(id);
EditTeacherData(teacher);
return View();
}
public JsonResult EditTeacherData( Teacher teacher)
{
return Json(teacher);
}
Ajax:
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
View:
#model StudentTeacher.Models.TeacherViewModel
#{
ViewData["Title"] = "EditTeacher";
}
<h1>EditTeacher</h1>
<h4>Teacher</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form id="AddTeacherForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TeacherId" id="TeacherId" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" id="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Designation" class="control-label"></label>
<input asp-for="Designation" class="form-control" id="Designation" />
<span asp-validation-for="Designation" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Education" class="control-label"></label>
<input asp-for="Education" class="form-control" id="Education" />
<span asp-validation-for="Education" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JoiningDate" class="control-label"></label>
<input asp-for="JoiningDate" class="form-control" id="JoiningDate"/>
<span asp-validation-for="JoiningDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" id="Submit" />
</div>
</form>
</div>
</div>
teacherService is a service that retrieves data that match with id. But it return null object. When I use this EditTeacherData(teacher); ajax not return a null object But in debugger model show value takes this function. I just wanna get an object through ajax and show data in the field via ajax.
Obviously, there is no parameter passed in to the controller in your ajax, so Edit method will never receive the parameter passed in.
You can implement it with EF core. If you want to use ajax, you can refer to this.
You can also achieve it without ajax, it much easier, please refer to this.
You are not sending data from your ajax request. Please read this for clear understanding
$('#Submit').click(function(){
var formData = $('#AddTeacherForm').serialize();
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
data: formData,
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
})

Preview an Image in Razor View

I want to be able to preview an image before posting the entire form for saving in the database. I want to reduce the amount of save buttons on the form. Currently, I can upload an image and preview it, but the other two images disappear, I have used a ViewBag to preview the images. I would like to do this without JS/JQuery and do it purely from an action and Razor View.
<div class="container">
<div class="row">
<div class="card" style="width:200px">
#using (Html.BeginForm("PreviewFront", "Goals", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<img class="card-img-top" src="#ViewBag.ImageFront" alt="Card image" style="width:200px;height:200px;">
<div class="card-body">
<p class="card-text">Before Front</p>
<div style="height:0px;overflow:hidden">
<input type="file" name="files" id="imageFront" />
</div>
<button type="button" onclick="chooseFront();"><i class="fa fa-file-image-o"></i></button>
<script>
function chooseFront() {
$("#imageFront").click();
}
</script>
<input type="submit" name="submit" value="ImageFront" id="imageFront" class="btn btn-primary" />
<br />
</div>
}
</div>
<br />
<div class="card" style="width:200px">
#using (Html.BeginForm("PreviewSide", "Goals", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<img class="card-img-top" src="#ViewBag.ImageSide" alt="Card image" style="width:200px;height:200px;">
<div class="card-body">
<p class="card-text">Before Side</p>
<div style="height:0px;overflow:hidden">
<input type="file" name="files" id="imageSide" />
</div>
<button type="button" onclick="chooseSide();"><i class="fa fa-file-image-o"></i></button>
<script>
function chooseSide() {
$("#imageSide").click();
}
</script>
<input type="submit" name="submit" value="ImageSide" id="imageSide" class="btn btn-primary" />
</div>
}
</div>
<br />
<div class="card" style="width:200px">
#using (Html.BeginForm("PreviewImage", "Goals", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<img class="card-img-top" src="#ViewBag.ImageBack" alt="Card image" style="width:200px;height:200px;">
<div class="card-body">
<p class="card-text">Before Back</p>
<div style="height:0px;overflow:hidden">
<input type="file" name="files" id="imageBack" />
</div>
<button type="button" onclick="chooseBack();"> <i class="fa fa-file-image-o"></i></button>
<script>
function chooseBack() {
$("#imageBack").click();
}
</script>
<input type="submit" name="submit" value="ImageBack" id="imageBack" class="btn btn-primary" />
</div>
}
</div>
</div>
</div>
My Action is as follows:
[HttpPost]
public ActionResult PreviewImage(HttpPostedFileBase files, string submit)
{
string f = DateTime.Now.ToString("ddmmyy-HHmmssffffff");
string e = Path.GetExtension(files.FileName);
string p = "~/Content/UserImages/Originals/" + f + e;
string physicalPath = Server.MapPath(p);
files.SaveAs(physicalPath);
string fn = Path.GetFileName(physicalPath);
switch (submit)
{
case "ImageFront":
ViewBag.ImageFront = GetImage(fn);
break;
case "ImageSide":
ViewBag.ImageSide = GetImage(fn);
break;
case "ImageBack":
ViewBag.ImageBack = GetImage(fn);
break;
}
return View("Create");
}
public string GetImage(string file)
{
string imgPath = Server.MapPath("~/Content/UserImages/Originals/" + file);
byte[] byteData = System.IO.File.ReadAllBytes(imgPath);
string imreBase64Data = Convert.ToBase64String(byteData);
string imgDataURL = string.Format("data:image/jpg;base64,{0}", imreBase64Data);
return imgDataURL;
}
I capitulated and did it with JQuery
function ImgPre(input) {
if (input.files[0]) {
var uploadimg = new FileReader();
uploadimg.onload = function(displayimg) {
$("#ImgPreview").attr('src', displayimg.target.result);
}
uploadimg.readAsDataURL(input.files[0]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Select the image <input type="file" id=" ImgUpload" onchange="ImgPre(this)" />
<button id="butImg">Upload</button>
<p>
<img id="ImgPreview" />
</p>

Saving data through AngularJS

Update:
I have replaced <input type=submit to <button ... and also remove the form tag from my html, after modifying my code i do not see it executing my JS and I have a debugger line in the code and it does not break....
I'm trying to POST data and I have all the code in placed and wired-up correctly (I believe) but when I try to Submit my page # My page gets refreshed, I don't see any event is firing and I have set debugger in the JS, and I do not see any JS error in developer tool
What I'm missing here apart from my code?
here is my code:
//HML code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS App</title>
<script src="../AppScripts/RequesterAdd.js"></script>
</head>
<body>
<form>
<div ng-app="requesterAddModule" ng-controller="requesterAddController" class="container">
<h2> add requester</h2>
<div ng-show="ShowMessage">Record saved Successfully</div>
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HostModel</h4>
<hr />
<div class="form-group">
<div>First Name:</div>
<div class="col-md-10">
<input type="text" ng-model="FirstName" required class="form-control input-lg" placeholder="First Name" />
</div>
</div>
<div class="form-group">
<div>Middle Name:</div>
<div class="col-md-10">
<input type="text" ng-model="MiddleName" required class="form-control input-lg" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<div>Last Name:</div>
<div class="col-md-10">
<input type="text" ng-model="LastName" required class="form-control input-lg" placeholder="Last Name" />
</div>
</div>
<div class="form-group">
<div>eMail Address:</div>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input type="text" ng-model="Email" required class="form-control input-lg" placeholder="Email Address" />
</div>
</div>
<div class="form-group">
<div>Is Host Active:</div>
<div class="col-md-10">
<input type="checkbox" ng-model="Active" required class="control-label col-md-2" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</form>
</body>
</html>
//JS:
var requesterAddModule = angular.module("requesterAddModule", []);
requesterAddModule.factory('requesterAddService',
['$http', function ($http) {
return {
addRequester: function (reqesterData) {
console.log(reqesterData);
debugger;
$http({
url: 'PersistRequester',
method: 'POST',
data: reqesterData
}).then (function (response) {
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
},
function(response) {
//failed
}
);
}
};
}]);
requesterAddModule.controller('requesterAddController', ['$scope', '$http', '$window', 'requesterAddService', function ($scope, $http, $window, requesterAddService) {
$scope.addRequester_ClickEvent = function () {
var req = {};
debugger;
req["FirstName"] = $scope.FirstName;
req["MiddleName"] = $scope.MiddleName;
req["LastName"] = $scope.LastName;
req["Email"] = $scope.Email;
req["Active"] = $scope.Active;
requesterAddService.addRequester(req);
}
}]);
//MVC Server side code:
[HttpPost]
public JsonResult PersistRequester(Requester requester)
{
var req = requester;
//if (ModelState.IsValid)
// {
req.CreatedDateTime = DateTime.Now;
db.Requesters.Add(requester);
db.SaveChanges();
return Json(new { Status = "Success" });
//}
}
You're using a form without a method and action which will by default post to the current url. I would highly recommend not to use a form or at least not using an <input type="submit" /> which will default in all the browsers to submit the form.
You're clearly using Bootstrap 3 here so why not just remove the form tag and the submit button and replace it with another element which will not trigger the form post and style it with class="btn btn-primary". Some could argue against this practise along the graceful degradation guidelines but since this particular form is not built from ground up to support the non-js scenario, it is best not to allow browser submit at all.
Also, in your service where you're doing the actual post, you specifically tell the page to reload.
if (response !== 'undefined' && typeof(response) == 'object') {
window.location.href = '/'
}
You should pass this data back to the viewmodel so that the view can re-render and display the response.
If you change the url, the view state is lost and the page will simply render again to the initial state.
instead line
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
please do
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" class="btn btn-primary" >Create</button>
I've just tested and is working for me replace:
<input type="submit" id="btnCreate" data-ng-click="addRequester_ClickEvent" value="Create" class="btn btn-primary" />
with
<button id="btnCreate" data-ng-click="addRequester_ClickEvent()" value="Create" class="btn btn-primary" >submit</button>
and I've change a bit your service to :
requesterAddModule.factory('requesterAddService',
['$http', function ($http)
{
return {
addRequester: function (reqesterData)
{
console.log(reqesterData);
debugger;
$http.post('PersistRequester', reqesterData).then(function (response)
{
if (response !== 'undefined' && typeof (response) == 'object') {
window.location.href = '/'
}
},
function (response)
{
//failed
}
);
}
};
}]);
it's posting to /home/PersistRequester if method 'PersistRequester' exist in other controller ie : foo controller change
$http.post('PersistRequester', reqesterData).then(function (response)
to $http.post('foo/PersistRequester', reqesterData).then(function (response)

Can we Made an anchor tag autoclick in the success function of Ajax Script?

Can we Made an anchor tag autoclick in the success function of Ajax Script?
Does it Possible we Click an anchor tag through Ajax Script?
if Yes then how?I am using Ajax in asp.net MVC?
This is the Viewsource of Partial View
<script language="javascript" type="text/javascript">
$(document).ready(function(){
alert("Button clicked");
$("#bt1").click(function(){
var data2 = $('#txt2').val();
var data1 = $('#Color').val();
$.ajax({
type:"Post",
url:'/Marker/CreateMarkerjson',
data:"Color="+ data1 + "&txt2=" + data2,
success:function(result)
{
alert(result);
$get('click').click();
},
error:function(result)
{
alert("fail");
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<form action="/Marker/CreateMarkerPartial" method="post">
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id" id="ID">
Id:</label>
<input type="text" id="txt1" />
</p>
<p>
<label for="CompanyName">
CompanyName:</label>
<input type="text" id="txt2" />
</p>
<p>
<label for="Color">
Color:</label>
<input id="Color" name="Color" type="text" value="" />
</p>
<p>
<input type="button" id="bt1" value="create" />
</p>
<div id="datepicker"></div>
</fieldset>
</form>
<div>
Back to List
click
</div>
Update answer. Merged the two $(document).ready functions and changed the $get('click') to $('#click'). Let's give it a try.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
alert("Button clicked");
$("#bt1").click(function () {
var data2 = $('#txt2').val();
var data1 = $('#Color').val();
$.ajax({
type: "Post",
url: '/Marker/CreateMarkerjson',
data: "Color=" + data1 + "&txt2=" + data2,
success: function (result) {
alert(result);
$('#click').click();
},
error: function (result) {
alert("fail");
}
});
});
$("#datepicker").datepicker();
});
</script>
<form action="/Marker/CreateMarkerPartial" method="post">
<fieldset>
<legend>Fields</legend>
<p>
<label for="Id" id="ID">
Id:</label>
<input type="text" id="txt1" />
</p>
<p>
<label for="CompanyName">
CompanyName:</label>
<input type="text" id="txt2" />
</p>
<p>
<label for="Color">
Color:</label>
<input id="Color" name="Color" type="text" value="" />
</p>
<p>
<input type="button" id="bt1" value="create" />
</p>
<div id="datepicker">
</div>
</fieldset>
</form>
<div>
Back to List click
</div>
you can fire the click handler of the anchor tag that you want clicked.
for example:
<a id="clickme" href="somelink.html">Click me</a>
now there must be an event being fired from your ajax script on the successful completion of the request. In that function do
document.getElementById('clickme').click();

Resources