Partial ASP.NET MVC View submit - asp.net

I'm new in ASP.NET MVC so the question could appear 'stupid', sorry.
I have a Partial View inside my Home view.
The Partial View submit a form calling an Action Method inside the HomeController.
It works fine with server validation, the problem is that after the post only the Partial View is rendered.
How can I render the entire Home view after post?
About the code:
Inside PartialView I have a form:
<% using (Html.BeginForm("Request", "Home")) { %>
Request is a ActionResult defined inside my HomeController.
[HttpPost]
public ActionResult Request(RequestModel model)
{
if (ModelState.IsValid)
{
// Saving data .....
}
else
{
// Show Server Validation Errors
return View();
}
}
At this time, after the post, the ascx shows the server validation erros but only the PartialView ascx code is rendered.
The Url looks like this after the post:
http://xxxxxxxxxxx/Home/Request
What I want is showing the entire Home view with the ascx inside showing server validation errors.

Try to do a partial submit using jQuery:
<script type="text/javascript">
$(document).ready(function () {
$("input[type=submit]").live("click", function () {
var f = $("input[type=submit]").parents("form");
var action = f.attr("action");
var serializedForm = f.serialize();
$.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data, textStatus, request) {
if (!data == "") {
// redisplay partial view
$("#formDiv").html(data);
}
else {
// do whatever on sucess
}
}
});
return false;
});
});
</script>
Assuming your view/ascx/HTML is something like this:
<div id="formDiv">
<% Html.RenderAction("Request"); %>
</div>

Change return type also:
[HttpPost]
public PartialViewResult Request(RequestModel model)
{
if (ModelState.IsValid)
{
// Saving data .....
}
else
{
// Show Server Validation Errors
return PartialView();
}
}

I was facing same issue in code, so I just made a small modification in my code and it worked.
Instead of returning the same view, I used
return Redirect(Request.Referrer)
Earlier:
return View();

Related

asp.net mvc add partial view dynamically using ajax

I am new to ASP.NET and I have a problem to add a content to my main view. In HtmlBeginform I upload the file on a button click and after file loading I need to display partial view under my main view I donĀ“t know how to call ajax script properly.
My main view:
#using prvniAplikace.Models;
#using Chart.Mvc.ComplexChart;
#using Chart.Mvc.Extensions;
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("LoadFile", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="form-group" align="left">
<label for="exampleInputFile">Load File</label>
<input type="file" accept=".tcx" class="form-control-file" name="exampleInputFile" id="exampleInputFile" aria-describedby="fileHelp">
</div>
<div class="form-group" align="left">
<button class="btn btn-primary" type="submit" id="add" name="add" value="Add">Display</button>
</div>
}
#section Scripts {
<script type="text/javascript">
$("#add").on('click', function () {
$.ajax({
async: false,
url: '/Home/getContent'
}).success(function (partialView) {
$('#getContent').append(partialView);
});
});
</script>
}
View I want to add to a main view:
#{
ViewBag.Title = "getContent";
Layout = null;
}
<h2>Obsah</h2>
<p>Odstavec</p>
<p>#DateTime.Now.ToString()</p>
Controller:
namespace prvniAplikace.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult getContent()
{
return PartialView("~/Views/Home/AjaxRequest.cshtml");
}
[HttpPost]
public ActionResult LoadFile(HttpPostedFileBase exampleInputFile)
{
if (exampleInputFile.ContentLength > 0)
{
var fileName = Path.GetFileName(exampleInputFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
exampleInputFile.SaveAs(path);
string xmlFile = Server.MapPath(fileName);
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.GetElementsByTagName("HeartRateBpm");
XmlNodeList nodes2 = doc.GetElementsByTagName("Time");
}
return RedirectToAction("Index");
}
}
}
As per your comment, you would like to load the partial view content via ajax after the index view is (re)loaded after the normal form submit you do to upload the file. To achieve this, you should make the ajax call in the document ready event. Since it is the same page/view user will see before and after the form submit, you should conditionally make the ajax call based on whether the page is loaded for your first GET request or for the GET request issued by the Redirect call in your http post action.
Since Http is stateless, there is no way for the GET action method to know whether this was called from the Redirect method call after successfully processing the submitted form (in your http post action). You may use TempData to address this problem. Before redirecting to the Index view, set a flag to the temp data dictionary which will be available in the next GET request.
[HttpPost]
public ActionResult LoadFile(HttpPostedFileBase exampleInputFile)
{
// your existing code here
TempData["Success"] = true;
return RedirectToAction("Index");
}
Now in your GET action, read this and pass it to view via ViewBag (or a view model property if you have one)
public ActionResult Index()
{
ViewBag.IsSuccess = TempData["Success"];
return View();
}
Now in the view, check this ViewBag item and if it exist and has true value, render the div in which we want to show the partial view content. You can take advantage of the the Url.Action helper method to generate the correct relative path to the action method which returns partial view and keep that in html5 data attribute in the div tag so we can use that in javascript later to make the ajax call.
So add this to your index view.
#if (ViewBag.IsSuccess!=null && ViewBag.IsSuccess)
{
<div data-url="#Url.Action("getContent", "Home")" id="myPartial"> </div>
}
Now all you need is the javascript code which makes the ajax call. Execute that in the document ready event. You can use the jQuery load method.
$(function(){
// Get the url from the data attribute of the div
var url = $("#myPartial").data("url");
// Make the ajax call using load method
$("#myPartial").load(url);
});

Validation in asp.net mvc

I have an action Create and method Save. The create action simply displays the view as shown below
public ActionResult Create()
{
return view();
}
In create view, i get few fields like Name, Address etc. Once the user enters the data and click on the save button, i call the Save method using ajax call.
In Save method, i am validating the data:
[HttpPost]
public bool Save(UserModel User)
{
if (ModelState.IsValid)
{
// save the data
return true;
}
else
{
return false;
}
}
the response of this method is used in ajax of Create View:
$(function () {
$("#btnSave").click(function () {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/Contoller/Save",
data:
// parameters
async: false,
success: function (data_l) {
if (data_l == true)
{
alert("record has been saved in database");
window.location.href = "#Url.Action("Index","Controller")";
}
else{
alert ("Invalid Entry");
window.location.href = "#Url.Action("Create","Controller")";
}
},
error: function () {
console.log("there is some error");
}
});
});
What i want to achieve is based on the response from the Save method, i should perform two operation. If the data is properly validated, data is saved and index page is loaded back. If validation is failed, i want to display the create view with fields entered along with validation messages.
I am sure that data annotation attributes are properly used in the model. Can someone please help me in solving this.
I suggest you perform validation on server side i.e. in your controller. Perform input validation first, if all fine, save the data on persistent store. If the data is saved successfully load index view or list view (whichever view you want by either return View() or RedirectToResult()). If there are any problem add an error in the ModelState object and return the same view. At client the error will be displayed along with the data already entered by user.
For an example refer below code snippet (there might be other ways however this is what we use at the moment):
public ActionResult AddNewSearch(SearchViewModel searchModel)
{
if (User.Identity.IsAuthenticated)
{
if (ModelState.IsValid)
{
var organizationUser = this.GetUser();
if (organizationUser == null)
{
ModelState.AddModelError("RecordNotFound", string.Format("No organization user found!!!"));
return RedirectToAction("LogOff", "Account");
}
if (this.searchService.GetUserSearch(organizationUser.Id, searchModel.Name) != null)
{
ModelState.AddModelError("RecordAlreadyExists", string.Format("Search already exists!!!"));
return View(searchModel);
}
var userSearchDomainModel = mappingService.Map<SearchViewModel, Search>(searchModel);
searchService.AddUserSearch(organizationUser, userSearchDomainModel);
return RedirectToAction("Index", "Search");
}
}
return RedirectToAction("Index", "Search");
}

Updating View with Model changes via Ajax Post - MVC3

I am trying to use an Ajax (I think) call to update my model value and then have that new value reflected in the view. I am just using this for testing purposes for the moment.
Here's the overview:
MODEL
public class MyModel
{
public int Integer { get; set; }
public string Str { get; set; }
}
CONTROLLER
public ActionResult Index()
{
var m = new MyModel();
return View("Test1", m);
}
[HttpPost]
public ActionResult ChangeTheValue(MyModel model)
{
var m = new MyModel();
m.Str = model.Str;
m.Str = m.Str + " Changed! ";
m.Integer++;
return View("Test1", m);
}
VIEW
#model Test_Telerik_MVC.Models.MyModel
#using Test_Telerik_MVC.Models
#{
ViewBag.Title = "Test1";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Test1</h2>
#if (false)
{
<script src="~/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui.min.js" type="text/javascript"></script>
}
<h2>
ViewPage1
</h2>
<div>
<input type="button" onclick="changeButtonClicked()" id="changeButton" value="Click Me!" />
<input type="text" value="#Model.Str" class="txt" id="str" name="Str"/>
<div></div>
</div>
<script type="text/javascript">
function changeButtonClicked() {
var url = '#Url.Action("ChangeTheValue", "Test1")';
var data = '#Model';
$.post(url, data, function (view) {
$("#Str").value = '#Model.Str';
});
}
</script>
Basically the view renders a button with a textbox. My sole aim is to simply display the value of my model (Str property) in the textbox.
I have tried various combinations of the changeButtonClicked() function to no avail. Test1 is the name of my controller. What I don't understand is when I debug it, the controller action fires and sets my values correctly. If I place a breakpoint on the "#Model.Str" section of the input tag, it shows me that my #Model.Str is equal to Changed! which is correct. However, as soon as my success function fires in the javascript, the value reverts back to it's original value.
I can make it work by changing the input type to submit and wrapping it in a #Html.BeginForm() section but I am wondering if/how to do it like this? Or is a Submit the only way to accomplish it?
Thanks
First thing in the jQuery the proper way to set a value of an input is to use:
$("#Str").val(#Model.Str);
Next we'll look at the controller. In the POST action result you are returning the entire View in your AJAX call. That means all the HTML, script references, and JavaScript are being returned in your jQuery post request. Since all you are trying to update is the value of the input named Str, I would just return that value as JSON and nothing else.
[HttpPost]
public ActionResult ChangeTheValue(MyModel model)
{
var m = new MyModel();
m.Str = model.Str;
m.Str = m.Str + " Changed! ";
m.Integer++;
return Json(m.Str);
}
Next I would place your HTML inputs in a <form> so you can have jQuery serialize your model for you and then you can change your jQuery post code to be:
function changeButtonClicked() {
var url = '#Url.Action("ChangeTheValue", "Test1")';
$.post(url, $('form').serialize(), function (view) {
$("#Str").val(view);
});
}
All the serialization is doing is encoding the inputs in your form into a string and if everything is named properly ASP.NET will bind that back to your model.
If you need to have your route handle both AJAX calls and full requests you could use ASP.NET's IsAjaxRequest function to test the request and return different results depending on if the request is AJAX or not. You would do something like this in your controller:
[HttpPost]
public ActionResult ChangeTheValue(MyModel model)
{
var m = new MyModel();
m.Str = model.Str;
m.Str = m.Str + " Changed! ";
m.Integer++;
if (Request.IsAjaxRequest) {
return Json(m.Str);
}
else {
return View("Test1", m);
}
}
In the ActionResult above you are doing everything you did before, but now are testing the request type and if it's AJAX you return a JSON result of your string value. If the request was not from an AJAX call then the full View (HTML, scripts, etc) are returned to be displayed in the browser.
I hope this is helps you out and is what you were looking for.
You can update the view, just not the model. The model in a razor page is compiled on the server in order to render the view; you would need to recompile the razor page after every ajax request.
Only real option is to return json from server and manually update DOM/View.

Message Control in Masterpage with ASP.NET MVC

Hey everyone. Got a custom on how to do this as im new to MVC and trying to get a couple of small things implemented. This is the way I did it in WebForms but want to transition it to MVC.
I have a user control that contains CSS which will render a message. This control is located in the MasterPage and called from a ASPX page like this:
Pseudo code:
try{
Msg.MessageMode = WebPageMessageMode.OK;
Msg.ShowOK("Report deleted.");
}
catch
{
Msg.MessageMode = WebPageMessageMode.ErrorMessage;
Msg.ShowError("There was a problem deleting the report.");
}
Masterpage.aspx
<cc1:WebPageMessage runat="server" ID="msg" />
I currently have the control in the MasterPage and now im a bit confused about proceeding from here.
Should I put the 'Msg' object above from the pseudo code to a View from the MasterPage?
What is the proper way to do something like?
I dont think there is a one-solution-fits-all here.
Anyway this is my solution that uses jQuery:
1) Create a MyResultModel class to handle a message to the user
public enum MyResultType { Info, Error }
public class MyResultModel
{
public MyResultModel( MyResultType type, string message ) {
switch ( type ) {
case MyResultType.Info: Title = "OK"; break;
case MyResultType.Error: Title = "Error!!!"; break;
}
Message = message;
}
public String Title { get; set; }
public String Message { get; set; }
}
2) Create a Partial View named MyResult in the Shared Folder to handle the model
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyResultModel>" %>
<div id="resultTitle"><%: Model.Title %></div>
<div id="resultMessage"><%: Model.Message %></div>
3) Create and use a BaseController for your controllers and add the following method to it. The method simply add a custom Http Header to the response
protected PartialViewResult PartialView( string viewName, object model, string resultHeader ) {
Response.AppendHeader( "MyHttpCustomHeader", resultHeader );
return base.PartialView( viewName, model );
}
4) In your action return a MyResultView when you've done
[HttpPost]
public virtual ActionResult DoSomething() {
try {
//Do Something
return PartialView( "MyResult",
new MyResultModel( MyResultType.Info, "Operation Completed" ),
"HttpResultInfo" );
}
catch ( Exception ex ) {
return PartialView( "MyResult",
new MyResultModel( MyResultType.Error, ex.Message ),
"HttpResultError" );
}
}
5) Finally, Submit the form using jquery and handle the results.
$.ajax({
type: "post",
dataType: "html",
url: "your/url/here",
data: $("#myform").serialize(),
success: function (response, status, xml) {
var resultType = xml.getResponseHeader("MyHttpCustomHeader");
if (resultType == null) {
//No message do whatever you need
}
else {
//response contain your HTML partial view here. Choose your
//desidered way to display it
}
}
});
With a scenario like this you dont need to place a control on the master page. You can:
Show the view as it comes from the action without any modification
Use some fancy message display technique as StackOverflow does with the orange sliding message (in this case simply extract the title and the message from the returned html)
Use some fancy jquery plugin as jGrowl to show your message
If you want to check wether it is an Info/Error message simply check the custom header with jQuery in the else branch
var title = $(response).filter("#resultTitle").text();
var message = $(response).filter("#resultMessage").text();
if (resultType == "HttpResultInfo") {
showInfoMessage(title, message);
}
else if (resultType == "HttpResultError") {
showErrorMessage(title, message);
}
Hope it helps!
In a controller, as part of the action, you can set a message like this:
public ActionResult MyAction()
{
// Do some stuff
TempData["message"] = "This is a message.";
return View("MyView");
}
In your master page or in your view:
<%
string text = TempData["Message"] as string;
Response.Write(text);
%>

ASP.NET MVC Controller FileContent ActionResult called via AJAX

The setup:
The controller contains a method public ActionResult SaveFile() which returns a FileContentResult.
What works:
The view contains a form, which submits to this action. The result is this dialog:
What doesn't work:
The view contains some javascript to do an AJAX call to the same controller action where the form would post. Rather than triggering the aforementioned dialog, or even the AJAX success function, the response triggers the AJAX error function, and the XMLHttpRequest.responseText contains the file response.
What I need to do:
Make the request for the file using AJAX, and end up with the same result as when submitting a form. How can I make the AJAX request provide the dialog that submitting a form shows?
Here's a quick example I made up. This is the concept LukLed was talking about with calling SaveFile but don't return file contents via ajax and instead redirect to the download.
Here's the view code:
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// hide form code here
// upload to server
$('#btnUpload').click(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '<%= Url.Action("SaveFile", "Home") %>',
success: function(fileId) {
window.location = '<%= Url.Action("DownloadFile", "Home") %>?fileId=' + fileId;
},
error: function() {
alert('An error occurred uploading data.');
}
});
});
});
</script>
<% using (Html.BeginForm()) { %>
<div>Field 1: <%= Html.TextBox("field1") %></div>
<div>Field 2: <%= Html.TextBox("field2") %></div>
<div>Field 3: <%= Html.TextBox("field3") %></div>
<button id="btnUpload" type="button">Upload</button>
<% } %>
Here's the controller code:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult SaveFile(string field1, string field2, string field3)
{
// save the data to the database or where ever
int savedFileId = 1;
// return the saved file id to the browser
return Json(savedFileId);
}
public FileContentResult DownloadFile(int fileId)
{
// load file content from db or file system
string fileContents = "field1,field2,field3";
// convert to byte array
// use a different encoding if needed
var encoding = new System.Text.ASCIIEncoding();
byte[] returnContent = encoding.GetBytes(fileContents);
return File(returnContent, "application/CSV", "test.csv");
}
public ActionResult About()
{
return View();
}
}

Resources