can we pass entire model to javascript asp.net mvc - javascript

I have a problem that on javascript call for the form submit , the model gets updated from controller ,but it is not updating in the view. I am thinking to update the model to new model values in javascript . so that the view shows the latest model values
can that be done?
thanks,
michael

Your question is extremely unclear and you provided no source code which makes things even more unclear. From the various comments you may have posted I assume that you are trying to update some model value inside the POST action without removing it from the model state and when the same view is rendered again the old values are displayed.
So I suppose you have a view model that looks something close to this:
public class MyViewModel
{
public HttpPostedFileBase File { get; set; }
public string SomeValue { get; set; }
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
SomeValue = "initial value"
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// Notice how the SomeValue property is removed from the
// model state because we are updating its value and so that
// html helpers don't use the old value
ModelState.Remove("SomeValue");
model.SomeValue = "some new value";
return View(model);
}
}
and a view:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<div>
<%= Html.LabelFor(x => x.SomeValue) %>
<%= Html.EditorFor(x => x.SomeValue) %>
</div>
<div>
<label for="file">Attachment</label>
<input type="file" name="file" />
</div>
<input type="submit" value="OK" />
<% } %>

Related

Updating the View with Model changes via Ajax Post by calling a javascript function

I use an Ajax call to update my model value and then have that new value should be shown in the view. Here is my code . In this code I am calling a method GetText and updating model value. How can I show the new model value in the html. Please help
public class EmpModel
{
public string EmpClaim {get;set;}
}
public IActionResult EmpClaim()
{
return View();
}
[HttpPost]
public ActionResult GetText(EmpModel model)
{
model.EmpClaim = "New Text" // This should be shown in view
return Json(data);
}
Html file
#model Test.Models.EmpModel
<div>
<input type="text" name="Claim" class="form-control" id="TxtClaim" asp-for="Claim" data-role="text"/>
</div>
<div>
<input type="button" onclick="changeText()" id="changeButton" />
</div>
Javascript
<script>
function changeText()
{
var url = '#Url.Action("GetText", "EmpDoc")';
$.post(url, $('form').serialize(), function (view) {
$("#TxtClaim").val(); // How can I update the TxtClim with model.EmpClaim "New Text"
});
}
</script>
You can use return Content() to return string to ajax function.
[HttpPost]
public IActionResult GetText(EmpModel model)
{
model.EmpClaim = "New Text" // This should be shown in view
return Content(model.EmpClaim);
}
Js:
<script>
function changeText()
{
var url = '#Url.Action("GetText", "EmpDoc")';
$.post(url, $('form').serialize(), function (view) {
$("#TxtClaim").val(view); // How can I update the TxtClim with model.EmpClaim "New Text"
});
}
</script>
Here is the result:
Note:
In your case, the model does not have a key field, so when you update the data, you cannot determine which piece of data to update. Further operations may require you to modify the model design.
You can refer to this.

Pass one extra parameter along with HttpPostedFileBase for Single File Upload

In my MVC application I have a View containing
1. One drop down list
2. One File Upload
3. One button for submitting the form.
form code (View)
<form id="upload" enctype="multipart/form-data" action="#Url.Action("ExcelUpload", "NBL")" method="POST">
#Html.DropDownList("CustomerName", new List<SelectListItem>
{
new SelectListItem() {Text = "Customer 1", Value="CM1"},
new SelectListItem() {Text = "Customer 2", Value="CM2"}
}, new { #class = "form-control", #style = "width:auto" })
<input type="file" name="fileUpload" id="fileUpload" size="23" style="margin-top:5px"/>
<button class="btn btn-primary">Upload</button>
</form>
I am able to pass my File in Controller successfully when I click the button.
Controller code
public ActionResult ExcelUpload(HttpPostedFileBase FileUpload)
{
if (FileUpload != null)
{
// Do Stuff here.
}
}
My Problem is I also want the drop down selected value in the controller when I click the button. How can I pass both the Drop down Selected value and the file together in the controller?
The name of the dropdown element is CustomerName and it's within the form. The browser will post it to the server as a key-value pair with the key being the name of the dropdown and the value will be the value the user has selected.
The MVC framework's default binder will look for an action named ExcelUpload that either has a parameter string customerName or the action has a complex type (Model) that has CustomerName as the property.
Change your action to:
ExcelUpload(HttpPostedFileBase FileUpload, string customerName)
The problem is your model as it is does not represent the view or data you want to use. So make a model like so:
using System.ComponentModel.DataAnnotations;
namespace Models
{
public class MyUploadModel
{
[Required]
public HttpPostedFileBase File { get; set; }
[Required]
public string CustomerName { get; set; }
}
}
Use that model in your views to generate the form and then in controller:
public ActionResult ExcelUpload(Models.MyUploadModel myModel)
{
if (ModelState.IsValid)
{
// all good, save
}
return View(myModel);
}
Of course you could just add a string-parameter to your action, but this is much more robust and represents the MVC-pattern (Model/View/Controller).

How to get Model value in javascript function and pass it to controller?

I have a Model on my CSHTML page that which I use this way:
#model Web.Models.Element
#using (Html.BeginForm("Search", "Company"))
{
#Html.HiddenFor(c => c.Person)
<div class="panel panel-default">
<div class="panel-heading"> Company Search</div>
<div class="panel-body collapse" id="screenCompanySearch">
<form id="formSearch" name="formSearch" method="post">
<fieldset style="margin: 20px;">
<legend>Search</legend>
<div class="row">
<div class="col-xs-2 col-sm-2">
#Html.Label("Company Name")
#Html.TextBoxFor(c => c.Company.Name, new { #class = "form-control" })
</div>
</fieldset>
</form>
</div>
</div>
My Javascript function is called by a button click this way:
$("#btnSearch").on("click", function() { searchCompany(); })'
In my JavaScript function I need to get this Model entirely loaded with the TextBoxFor values:
<script type="text/javascript">
function searchCompany() {
var data = $("#formSearch").serialize();
$.ajax({
url: "#(Url.Action("SearchCompany", "Company"))",
cache: false,
data: data,
type: "POST",
success: alert("sucesso!")
});
}
</script>
My Controller method is being loaded correctly, but the model passed in the Ajax "data" parameter is not filled with the TextBoxFor values.
This is my Controller ActionResult for the View:
public ActionResult Consulta()
{
Element model = new Element();
model.Person = new Person();
return View(model);
}
What is happening is that my Model is being instantiated on my Controller but the values from the TextBoxFor is not recorded on the properties of the Model.
How can I solve this? Thanks for now.
UPDATED
<div class="col-xs-2 col-sm-2">
#Html.Label("Person Name")
#Html.TextBoxFor(c => c.Person.Name, new { #class = "form-control" })
</div>
So, 'c' equals my Element object. When I reach the Controller Method "Search", the parameter Element passed via ajax call does not instantiate the Element.Person which gives me Person = null.
In my ActionResult I have:
Element model = new Element();
model.Person = new Person();
Element class:
public Element()
{
this.Contacts = new List<Contact>();
this.DataType = new DataType();
}
public int ID_Element { get; set; }
public int ID_ElementType { get; set; }
public virtual List<Contact> Contacts { get; set; }
public virtual DataType DataType { get; set; }
public virtual Person Person {get; set; }
Controller Action
[HttpPost]
public JsonResult SearchCompany(Element model)
{
...
}
The serialize method is not giving your the serialized version of the form because you have nested form tags.
The #using (Html.BeginForm("Search", "Company")) will create an outer form tag and you have your other form inside that, hence creating a nested form structure. Nested forms are invalid. You can have 2 forms in the same page, parallel to each other, not nested.
If you fix the nested form issue, the serialize method will give you valid string for you form inputs.
#using (Html.BeginForm("Search", "Company"))
{
<!-- Your other form -->
}
<form id="formSearch" name="formSearch" method="post">
<fieldset style="margin: 20px;">
<legend>Search</legend>
<div class="col-xs-2 col-sm-2">
#Html.Label("Company Name")
#Html.TextBoxFor(c => c.Company.Name, new { #class = "form-control" })
</div>
</fieldset>
</form>
Keep in mind that, the serialize method will give you the input element values of items inside this specific form. If you want to send some other data (ex : Id), you need to keep that in an input field inside this form.

RadioButtonFor in mvc shows required validation even though not applied required validation

I have one view in which I put two radio button for attribute in my model
I just put data annotation for other field but not the radiobutonfor field but steel it show required validation.Below is my code.I the attribute is int type in model.I used javascript unobtrusive library inn view as well.
<td>
<label>#Html.RadioButtonFor(m => m.OneToOne, 1) Hours </label>
<label>#Html.RadioButtonFor(m => m.OneToOne, 2) Unit </label>
</td>
I am using Html.begin from to post this value.
The RadioButtonFor helper method generates html markup for the radio button input with data-val-required attribute unless you specify the property as nullable type! The jQuery validate plugin does validation on this input because of the existence of this attribute.
If you do not want client side validation on this input, You should change the property type from int to nullable int(int?).
public class YourViewModel
{
// Other properties
public int? OneToOne { set; get; }
}
If radio buttons are not required to select, I personally like to use mutually exclusive checkboxes.
Mainly, if a user accidental selects a radio button, s/he won't be able to uncheck it back unless the user refreshes the entire page. I feel like it is really annoying.
Sample at jsfiddle.net
Model
public class ViewModel
{
public bool OneToOneHours { get; set; }
public bool OneToOneUnit { get; set; }
}
View
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post))
{
<div class="form-control">
#Html.CheckBoxFor(model => model.OneToOneHours, new {#class = "mutually-exclusive"}) Hours
#Html.CheckBoxFor(model => model.OneToOneUnit, new {#class = "mutually-exclusive"}) Unit
</div>
<button id="btnSubmit" type="submit">Submit</button>
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('input.mutually-exclusive').click(function () {
var checkedState = $(this).val();;
$('input.mutually-exclusive').attr("checked", false);
$(this).prop("checked", checkedState);
});
</script>
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(ViewModel model)
{
int? oneToOne;
if (model.OneToOneHours)
oneToOne = 1;
else if (model.OneToOneUnit)
oneToOne = 2;
return View(model);
}
}

ASP.NET MVC 4 - Partial views and Ajax.Actionlink

I am trying to put on my homepage some link that render partial views - I want to display some info from the database when users click a link: the link should be replaced by text on the same page. I followed a tutorial but I cannot get it to work in my project. Here is what I have:
My Home/Index view:
<div id="NeZaman">
#Ajax.ActionLink("Ne Zaman Gelcekmiş?", "NeZaman", new AjaxOptions {
UpdateTargetId="NeZaman",
InsertionMode = InsertionMode.Replace,
HttpMethod="GET" })
</div>
My HomeController:
private CaglaContext db = new CaglaContext();
public PartialViewResult NeZaman()
{
var neZaman = db.Caglas.Where(c => c.Id == 1).Select(c => c.NeZamanGelcek).FirstOrDefault();
return PartialView("_NeZaman", neZaman);
}
My partial view (_NeZaman.cshtml):
#model caglageldimi.Models.Cagla
<p>
#Model.NeZamanGelcek
</p>
My Model(Cagla.cs):
public class Cagla
{
public int Id { get; set; }
public bool GeldiMi { get; set; }
public string NeZamanGelcek { get; set; }
public string Nerdeymis { get; set; }
}
So I'm passing in a neZaman value that the partial view is supposed to use, but how?
You've set your patial view's model to your class:
caglageldimi.Models.Cagla
But you're passing a string:
db.Caglas.Where(c => c.Id == 1).Select(c => c.NeZamanGelcek).FirstOrDefault();
Your select statement is only grabbing the "NeZamanGelcek" string property value to send to your partial view.
Changing your partial view's model to System.String should fix it:
#model System.String

Categories

Resources