Upload a file before form submission - asp.net-mvc

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();
}
}

Related

PartialView with model in View with out model

Hello is it possible to run PartialView with model inside View without model, or I have to create model which will contains models for partial views?
Example:
User have his site:
#{
ViewBag.Title = "MyPanel";
}
<div class="jumbotron">
<!--Right Menu-->
<div id="RightMenu" class="col-md-10" style="max-height:550px; overflow-y:scroll;">
#Html.Action("AllSongs","UserPanel")
</div>
</div>
</div>
I would like to Render PartialView AllSongs which contains model.
public PartialViewResult AllSongs() {
var userId = (int)Session["Login"];
var songs = context.Songs.Where(x => x.UserID.Equals(userId));
return PartialView(songs);
}
But when code go inside this method I got error like this:
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'
You can do this, however that action is going to load different that what you are expecting. I think you would want that to load outside of what else is going on. If that is the case you could return the content of that partial and place it in an element --> $('#MyDiv').html('#Model.AllSongsHtmlContnet'); You can use a helper function in your controller to return something like:
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();
}
}

How to stop postback in ajaxbeginform in asp.net mvc

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();
}
}

How can send List<> Model From View To Controller using Ajax Jquery in Mvc3 asp.net?

How Can I Send List<int> Roles Model? For example from view To Controller.
Using Ajax Jquery in Mvc3 asp.net not razor.
I'm using this code
var url = '<%:Url.Action("Roles","RolesManager") %>';
$.ajax({
url: url,
type: 'post',
dataType: "json",
traditional: true,
data: $('#EditUserForm').serialize(),
success: function () {
$('#EditUserForm').submit();
},
error: function () {
}
});
but when I debug the controller List<int> Roles = null.
mode in page like
<%: Html.ListBoxFor(m => m.UserRoles, new MultiSelectList(Model.UserRoles, "UserRoleId", "UserRoleName"), new { #id = "UserRoles", #class = "ddlUserRolesCls" })%>
It's a Model Bind List, in this case, you have to send the information using the same name of your parameter in the name attribute of html inputs tag and asp.net model binder will convert it on a collection on the post. Your javascript looks fine. Try something like this:
In the view:
<input type="text" name="roles" value="1" />
<input type="text" name="roles" value="4" />
<input type="text" name="roles" value="2" />
<input type="text" name="roles" value="8" />
in the controller:
public ActionResult Post(List<int> roles)
{
// process
}
Also take a look at this article:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Change your viewmodel like this. Note that we have a SelectedUserRoles property of type int array.
public class EditUserRole
{
public List<SelectListItem> UserRoles{ get; set; }
public int[] SelectedUserRoles { set; get; }
//Also other relevant properties here
}
And in my Get Action, fill the UserRoles property
public ActionResult EditUser(int id)
{
var vm=new EditUserRole();
vm.UserRoles=GetUserRoles();
}
public List<SelectListItem> GetUserRoles()
{
var roles= new List<SelectListItem>();
// the below is hardcoded. Get it from DB And fill it here
roles.Add(new SelectListItem { Value="1",Text="Admin" });
roles.Add(new SelectListItem { Value = "2", Text = "Editor" });
return roles;
}
and in your view which is strongly typed to EditUserRole,
#Html.ListBoxFor(m => m.SelectedUserRoles,
new MultiSelectList(Model.UserRoles, "Value", "Text"),
new { #id = "UserRoles", #class = "ddlUserRolesCls" })
When you post your form, you will get the selected Roles ID in the SelectedUserRoles property of the posted model.
[HttpPost]
public ActionResult Edit(EditUserRole model)
{
// check model.SelectedUserRoles
// to do : Save and redirect
}

ASP.NET MVC: How to include PartialView in custom html?

I have TinyMCE editor in my custom site CMS and store HTML content in SQL DB.
Then I render it in cshtml RazorView:
#MvcHtmlString.Create(Model.Content)
How can I include PartialView inside html content by TinyMCE?
Something like:
...content html...
<div>[[ViewName]]</div>
...content html...
A partial view can be included in an HTML page by using the following
<% Html.RenderPartial("~/Views/Folder/ViewName.ascx");%>
You could execute the Partial View and set the resultant html as the content for TinyMCE.
private string ProduceViewResult(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.ToString();
}
}
Usage
var partialViewHtml = ProduceViewResult("PartialViewName", myModel);

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