How to stop postback in ajaxbeginform in asp.net mvc - postback

using (Ajax.BeginForm("Customer", new AjaxOptions { HttpMethod = "POST" }))
{
{
.................
}
}
How can ı disable postback in new ajaxoptions , what to write ?

You need to use Json in order to prevent full postback in your page.
After that you must return to Partial View.
As instance;
HTML Code:
<input type="text" id="UserName" name="UserName"/>
<input type="button" onclick="ButonClick()" value="Enter"/>
Javascript Code:
function ButonClick() {
var data= {
UserName: $('#UserName').val(),
};
$.ajax({
url: "/Home/MyActionResult",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),
Controller:
public ActionResult MyActionResult(string UserName)
{
var stringView = RenderRazorViewToString("_YourPartialView", model);
return Json(stringView, JsonRequestBehavior.AllowGet);
}
Note:
You need below code to render your partial view for json.
Add below to your controller too.
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}

Related

Couldn't Load the data on Dropdown menu using Asp.net Mvc Json

i am creating a simple inventory control system using Asp.net Mvc Json.when i am tring to load the category data.category Data is not loaded to the Dropdown menu. code which i tried so far i attached below along with the screen shot image.
enter image description here
Form design
<div class="card-action">
<div class="form-group">
<label class="form-label">Category</label>
<select class="form-control" id="category" name="category"
placeholder="Category" required>
<option value="">Please Select</option>
</select>
</div>
</div>
Jquery
getCategory();
function getCategory() {
$.ajax({
type: 'GET',
url: '/product/Getcategory',
dataType: 'JSON',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
$('#category').append($("<option/>", {
value: data[i].id,
text: data[i].cat_name,
}));
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
Controller
public class ProductController : Controller
{
aspoEntities db = new aspoEntities();
// GET: /Product/
public ActionResult Index()
{
return View();
}
public ActionResult Getcategory()
{
using (aspoEntities db = new aspoEntities())
{
var category = db.categories.ToList();
return Json(new { data = category }, JsonRequestBehavior.AllowGet);
}
}
}
Change your controller to
public class ProductController : Controller
{
// GET: /Product/
public ActionResult Index()
{
return View();
}
public ActionResult Getcategory()
{
aspoEntities db = new aspoEntities()
var category = db.categories.ToList();
return Json(category, JsonRequestBehavior.AllowGet);
}
}
It seems your db context has been disposed before the json is being serialized.
Try to inject the db context to your controller and get rid of the using statement.
Or move your return statement outside the using block.

Knockoutjs couldn't go to RedirectToAction view

I have a simple login controller:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(string userName, string passWord)
{
if (ModelState.IsValid)
{
var employee =
db.Employees.FirstOrDefault(x => x.EmployeeNo == userName && x.Password == passWord && x.StatId == 1);
if (employee != null)
{
return RedirectToAction("Index");
}
}
return View();
}
public ActionResult Index()
{
return View(db.Employees.ToList());
}
This is my view which is bound to a knockoutjs file:
#model SimpleLogin.Models.Employee
#{
ViewBag.Title = "Login";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Login</h2>
<span>User</span> <span data-bind="text: userName"></span> <br/>
<span>Password</span> <span data-bind="text: passWord"></span>
<div>
<table>
<tr>
<td>
<input type="text" name="txtUserName" placeholder="User Name" data-bind="value: userName" /></td>
</tr>
<tr>
<td>
<input type="password" name="txtPassword" placeholder="Password" data-bind="value: passWord"/></td>
</tr>
</table>
<button data-bind="click: logUser">Login</button>
</div>
#section Scripts
{
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/knockout")
#Scripts.Render("~/Knocks/LoginVm.js")
}
this is my knockout LoginVm.js
$(function() {
ko.applyBindings(LoginVm);
});
var LoginVm = {
userName: ko.observable(''),
passWord: ko.observable(''),
logUser: function() {
var self = this;
$.ajax({
url: '/Company/Login',
type: 'post',
dataType: 'json',
data: ko.toJSON(self),
contentType: 'application/json',
success: function(data) {
//window.location.href = '/Company/Index'; //I tried putting an alert here but doesn't work. why?
}
});
}
};
When I ran the app, I put a break point in the "if (ModelState.IsValid)" of the controller. It worked fine. It even executed the "return RedirectToAction("Index")" but the problem is, the page stays in the Login View and never loaded the Index view. Why? What did I do wrong?
I also put this:
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-2.1.0.js",
"~/Scripts/knockout-2.1.0.debug.js"));
in the BundleConfig.cs
I'm not used to js, it really confuses me. I know there are more than 2 errors in what I did.
this is my class
public class Employee{
public int EmployeeId {get; set;}
public string UserName {get; set}
public string Password {get; set;}
}
You can't return View to an ajax request. You should change it to:
public ActionResult Login(string userName, string passWord)
{
if (ModelState.IsValid)
{
var employee =
db.Employees.FirstOrDefault(x => x.EmployeeNo == userName && x.Password == passWord && x.StatId == 1);
if (employee != null)
{
return Json(true);
}
}
return Json(false);
}
Then in your js:
$.ajax({
url: '/Company/Login',
type: 'post',
dataType: 'json',
data: ko.toJSON(self),
contentType: 'application/json',
success: function(data) {
if(data) {
window.location.href = '#Url.Action("Index", "Company")';
}
}
});
But there is no need to use knockout here. You can simply do a regular form Submit and Redirect by return RedirectToAction("Index", "Company") in the controller.

Upload a file before form submission

I have a form to apply for a job.In which the user should be allowed to upload a resume,also the form have a dropdown that allow the user to select from the list of previously uploaded resume.Now to my question,I need the new resume to be uploaded without form submission and repopulate the dropdown with the newly uploaded resume.So the user now can apply the job by selecting the resumes listed in dropdown.Any help please?
You need to use Json in order to prevent full postback in your page. After that you must return to Partial View.
As instance;
HTML Code:
<input type="text" id="UserName" name="UserName"/>
<input type="button" onclick="ButonClick()" value="Enter"/>
Javascript Code:
function ButonClick() {
var data= {
UserName: $('#UserName').val(),
};
$.ajax({
url: "/Home/MyActionResult",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data)
});
Controller:
public ActionResult MyActionResult(string UserName , MyModel model)
{
var stringView = RenderRazorViewToString("_YourPartialView", model);
return Json(stringView, JsonRequestBehavior.AllowGet);
}
Note:
You need below code to render your partial view for json.
Add below to your controller too.
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}

MVC3 ajax update a field in strongly typed partial view

I have some trouble play with MVC3.
I have a strongly typed partial view contains a form. it is embedded in a big page. I want to submit this partial view to controller and to update some fields. After the updating I expect the partial view embedded in the page being replaced with the html contains new values becuase the UpdateTargetId is declared, but it is not. Do not know if I can achieve that. Any help will be appreciated. The code as:
public ActionResult Employee(Employee em)
{
var em1 = new Employee
{
Id = 1,
Name = "xing yanguang",
Code = "131324e12"
};
return PartialView(em);
}
The code in the partial view:
Try this
modify your partial view
//In Partial View
#model MvcApplication1.Employee
<table>
<tr>
<td>
#Html.TextBoxFor(m => m.Id)
</td>
<td>
#Html.TextBoxFor(m => m.Name)
</td>
<td>
#Html.TextBoxFor(m => m.Code)
</td>
</tr>
</table>
Now in your parent view
// In View.cshtml
<div id="div_employee">
#Partail("partailView",Model)
</div>
#using (Ajax.BeginForm("Employee", "PO", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div_employee", InsertionMode = InsertionMode.Replace }))
{
<input type="submit" value="save" />
}
In Controller
public string Employee(Employee em)
{
var em1 = new Employee
{
Id = 1,
Name = "xing yanguang",
Code = "131324e12"
};
return RenderPartialViewToString("partailView",em1);
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
In controller add one more method to get RenderHtml of partial view, by passing PartailViewName and model to RenderPartialViewToString method it will return Htmlstring of view with updated values.

Transfer return data of ajax post to hidden? ASP.NET MVC

i have four different forms on my page and each are ajax forms.
I'm sending post request for first form with ajax to MVC Controller, it basically returns ViewData["TEST"] back to me.
I want to use ViewData on my view and i need set this to a hidden field for use other forms.
How i can reach it without using normal submit ?
Here is my code:
#using (Ajax.BeginForm("Index", new AjaxOptions{ HttpMethod = "POST" }))
{
<script type="text/javascript"> alert('#(ViewData["TEST"])'); </script>
<input type="text" name="name" />
<input type="button" onclick="javacript:SubmitAjax();" />
}
<script type="text/javascript">
function SubmitAjax() {
$.ajax({
type: 'POST',
data: $("#form0").serialize(),
url: "/Home/Index",
timeout: 2000,
async: false,
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(message_Error);
}
});
}
And Controller;
[HttpPost]
public ActionResult Index(string name)
{
ViewData["TEST"] = "TESTSTRING";
return View();
}
No ViewData !!!! . Simply return the content.
[HttpPost]
public ActionResult Index(string name)
{
return Content("TESTSTRING");
}
and to set this in the hidden field,you can do so int he success event of your ajax function
success: function (data) {
$("#hiddenElementID").val(data);
},
Also do not hard code the Path to action method like that. Always make use of the HTML helper methods.
Replace
url: "/Home/Index"
with
url: "#Url.Action("Index","Home")"
I personally prefer to avoid the AjaxBeginForm method and would like to write some clean handwritten javascript code to handle this.
#using(Html.Beginform())
{
<input type="text" name="name" />
<input type="submit" id="saveName" value="Save" />
}
<script type="text/javascript">
$(function(){
$("#saveName").click(function(e){
e.preventDefault();
$.post("#Url.Action("Index","Home")",
$(this).closest("form").serialize(),
function(data){
$("#yourHiddenElementID").val(data);
});
});
});
</script>
EDIT : As per the comment.
If you want to return multiple items, You can return JSON
Ex 2 : returning anonymous type to JSON
[HttpPost]
public ActionResult Index(string name)
{
return JSON(new { status : "true", ItemCount=35, UserName="Marc"} );
}
Ex 1 : returning a ViewModel to JSON
Assuming you have a class like
public class Result
{
public string Status { set;get;}
public int ItemCount { set;get;}
public string UserName { set;get;}
}
Now you can use this class and return it as JSON
[HttpPost]
public ActionResult Index(string name)
{
return JSON(new Result { Status : "true",
ItemCount=25, UserName="Scott"} );
}

Resources