Showing values from controller in view in asp.net mvc - asp.net-mvc

I have a form, with different input fields, where user can enter their information.
Inside of the form, I have 2 buttons. When user clicks one button called 'Add address', I want to fill up a div with the address. And when user clicks other button called 'Preview', the form is validated and prepared for preview page.
Below is how 'My Adrress' button is defined in Index.cshtml
<button id ="address" class="btn btn-default" onclick="location.href='#Url.Action("populateAddress","Information")?addressID=2222'">
Add Address
</button>
So, when user clicks, Add Address, I want to fill up the address that I am retrieving from database in the div on Index.cshtml. Below is where I want to display the retrieved address:
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-3">
#Html.Label("Address", htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-6">
#ViewBag.FeedAddress //Here I want to display my retrieved address
</div>
</div>
So, on button click, I am calling my 'Information' controller method 'populateAddress' and passing the addressID parameter '2222' to it.
Below is how I am defining my 'populateAddress' method in my controller:
public void populateAddress(string addressID = null)
{
var addressDetail = db.Agency.Where(e => e.AddressCode == addressID).ToList();
string AddressRetrieved= "";
string StreetAddress, City, State, Zip = "";
foreach(var detail in addressDetail )
{
StreetAddress = detail.Address;
City = detail.City;
State = detail.State;
Zip = detail.Zip;
AddressRetrieved= StreetAddress + Environment.NewLine + City + ", " + State + " - " + Zip;
}
ViewBag.FeedAddress = AddressRetrieved
}
So, here, my ViewBag is getting filled with my retrieved address.
But, my issue is, after it gets filled with the address, instead of showing it on my Index.cshtml page in the div where I am retrieving back the value from ViewBag, my page is instead getting submitted and showing my validations.
I want that, once user fills up part of the form above 'Add Address' button and clicks 'Add Address' button, my address is retrieved from ViewBag, shown inside the div and user proceed filling up the rest of the form.
I am unable to get this kind of behavior.
Can anyone please help me to achieve that behavior or may be tell what I am missing. Thanks!
EDIT:
Please find Index.cshtml code. The page is long, so I am just adding required code:
// input fields for user
<div class="form-group">
<div class="col-md-2">
#Html.Label("Title", htmlAttributes: new { #class = "control-label" }) </div>
<div class="col-md-6">
#Html.EditorFor((e => e.Title), new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
//Add Address button
<button id ="address" class="btn btn-default" onclick="location.href='#Url.Action("populateAddress","Information")?addressID=2222'">
Add Address
</button>
//section to display retrieved address
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-3">
#Html.Label("Address", htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-6">
#ViewBag.FeedAddress //Here I want to display my retrieved address
</div>
</div>
// input fields for user
<div class="form-group">
<div class="col-md-2">
#Html.Label("Description", htmlAttributes: new { #class = "control-label" }) </div>
<div class="col-md-6">
#Html.EditorFor((e => e.Description), new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
//Preview Button
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<input type="submit" value="Preview" class="btn btn-default" />
</div>
</div>

In the controller (named mainController for this example):
public JsonResult GetAddress(int addressId)
{
// do whatever to get what you need
// the Address model will need to be JSON serialized
return JSON(Address);
}
In the javascript:
function GetAddress(addressId)
{
$.ajax({
type: "GET",
async: false,
url: "/main/GetAddress?addressId=" + addressId
contentType: "application/json",
context: this,
success: function (data) {
console.log(data);
// do stuff here
},
error: function (error) {
alert("error");
}
});
}
Important routing info:
The url is "/main/GetAddress/" which means it will route to the controller mainController (notice the 'main' part matches) and the function inside the controller is GetAddress. It is a "GET" request so using the url variable is fine.
This is the basic structure of how you do an ajax call with MVC.
Special note: In the controller method you return a JsonResult, NOT an ActionResult! Use ActionResult when you are trying to route through a View and have the Razor engine create the HTML markup. But if you are just returning JSON, use JsonResult.
EDIT:
In case you want to do a POST instead of a GET, here is what it would look like:
In the controller:
public JsonResult PostSomething(MyClass data)
{
// do something with the data -- class is MyClass
var result = ...... // whatever the result is, Null is ok I'd recommend some sort of "successful" reply
return JSON(result);
}
In the javascript:
function SubmitForm()
{
var formData;
// common to use jQuery to get data from form inputs
// use JSON.stringify to serialize the object
var data = JSON.stringify(formData);
// the ajax is almost the same, just add one data: field
$.ajax({
type: "POST",
url: "/main/PostSomething"
contentType: "application/json",
data: data, // the second 'data' is your local variable
success: function(data){
console.log(data);
},
error: function(error){
alert(error)
}
});
}
The 'asynch: false' and 'context: this' from the first example are actually not necessary in either (most of the time).
As with most of programming, there is more than one way to do it. These examples are just simple (but fairly standard) snippets to get you on the right track.

Related

Multiple submits to different MVC controller actions from buttons or dropdownlist changes

If I have a single form - with two submits:
From a save button - calls a form POST "Save" controller action.
From a change of a dropdown list value - calls a form POST "NoSave" controller action that returns a modified view without saving.
What's the best way of achieving this?
At the moment, I have the following - but they both call the same POST controller action. I want to call a named action for the dropdownlist update.
<form form method="POST">
<!-- dropdown list -->
<div class="row">
#Html.LabelFor(x => x.FieldName, "Field Name:")
#Html.DropDownListFor(x => x.FieldName, Model.FieldName, new { #class = "browser-default", #onchange = #"form.submit();" })
#Html.ValidationMessageFor(x => x.FieldName)
</div>
</div>
<!-- save button-->
<div class="save-button">
<input type="submit" class="btn" value="Save" />
</div>
</form>
what about using ajax request for different type of requests every type of request call different action or even different controller
[HttpPost]
public ActionResult SomeFunction(string a)
{
return Json("some data here", JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult AnotherSomeFunction(string a)
{
return Json("some data here", JsonRequestBehavior.AllowGet);
}
//by click button
$("some button name ").click(function(){
$.ajax({
url: 'home/FirstAjax',
success: function(responce){ alert(responce.data)},
error: function(responce){ alert(responce.data)}
});
});
//by click another button
$("some button name ").click(function(){
$.ajax({
url: 'home/SecoundFirstAjax',
success: function(responce){ alert(responce.data)},
error: function(responce){ alert(responce.data)}
});
});
For this you can use ajax.beginform in first parameter you have to give the name of action and then controller and then some option which are like method type and success and failure actions.
#using (Ajax.BeginForm("_LoadPartial", "Abss", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
<div class="row">
#Html.LabelFor(x => x.FieldName, "Field Name:")
#Html.DropDownListFor(x => x.FieldName, Model.FieldName, new { #class = "browser-default", #onchange = #"form.submit();" })
#Html.ValidationMessageFor(x => x.FieldName)
</div>
</div>
<!-- save button-->
<div class="save-button">
<input type="submit" class="btn" value="Save" />
</div>
}
Also provide OnSuccess and Failure Javascript fucntion on the same page.
<script>
function OnSuccess(){
// some action
}
function OnFailure(){
// some action
}
</script>

how to store user input value in local variable(in view) in asp.net mvc 5?

i want to declare a local variable in my razor html form (view) and want to store user input value in that local variable.And then want to use that variable in foreach loop .in mvc 5 i am new to asp.net.
#using (Html.BeginForm("AddQuestion", "admin", new { id = ViewBag.qf_id }, FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-group">
<label>Question Statement</label>
#Html.TextBoxFor(a => a.Ques.QuestionString, new { #class = "form-control" })
#Html.ValidationMessageFor(a => a.Ques.QuestionString)
</div>
<div class="form-group">
<label>No. of option you want to add for this question </label>
<div class="col-md-4">
#{var val = #Html.TextBoxFor(a => a.counter, new { #class = "form-control" }); }
</div>
</div>
foreach(var item in val)
{
#Html.TextBoxFor(a=>a.Ans.AnswerStatement)
}
<div>
<button class="btn btn-primary" type="submit">Add</button>
</div>
}
What you are trying to do won't work unless it gets adapted to 1 of 2 solutions:
1) The only way this works is if the use enters a value in the textbox, then posts back to the controller, and the controller inputs this variable into the model, which the view then re-renders, using the number in the model, with the desired number of entries. That's the web forms way and is inefficient.
2) Using JavaScript, when a user enters a number, JavaScript can either render the markup using a templating framework, or make a request to the server, get the individual data, and return a partial view as HTML.

Live search MVC

I'm looking for live search for ASP.NET and entity framework. I'm a little bit green with it. I read that it needs to use ajax, but I never used it before and can't get good example. Here is a piece of code, cshtml (part of textbox)
<div class="form-horizontal">
<hr />
<h4>Search for a client: </h4>
<div class="input-group">
<span class="input-group-addon" id="Name">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Name", "", new { #class = "form-control", placeholder = "Name" })
</div>
<div><h6></h6></div>
<div class="input-group">
<span class="input-group-addon" id="Surname">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
</span>
#Html.TextBox("Surname", "", new { #class = "form-control", placeholder = "Surname" })
</div>
<div><h6></h6></div>
<button type="submit" class="btn btn-default" data-toggle="modal" data-target="#infoModal">Search</button>
</div>
this is a part of controller:
public ActionResult Index(string Name, string Surname)
{
var SearchList = from m in db.Klienci
select m;
if (!String.IsNullOrEmpty(Name))
{
SearchList = SearchList.Where(s => s.Name.Contains(Name));
}
if (!String.IsNullOrEmpty(Surname))
{
SearchList = SearchList.Where(s => s.Nazwisko.Contains(Surname));
}
return View(SearchList);
}
So it search for me clients by name and surname, but it refresh full page when it lost focus or after clicking the button. How to solve it, to get live search? after each keystroke search through database? I'm a little bit green, would you Help me?
You can listen to the keyup event on your input element, read the value and send it to the server using ajax. Return the results and in the ajax call's success callback, update the ui with the results.
$(function() {
$("#Name,#SurName").keyup(function(e) {
var n = $("#Name").val();
var sn = $("#SurName").val();
$.get("/Home/Index?Name="+n+"&SurName="+sn,function(r){
//update ui with results
$("#resultsTable").html(r);
});
});
});
The code basically listens to the key up event on the two input textboxes and read the values and send to the /Home/Index action method using jquery get method asynchronously.When the action method returns the response, we update the DOM.
Assuming resultsTable is the Id of the table where we list the results.
Also, since you are returning the partial view result ( without layout headers), you should use return PartialView() instead of return View()
if(Request.IsAjaxRequest())
return PartialView(SearchList);
return View(SearchList);
Here is nice example/tutorial how to use Ajax with ASP.NET MVC
http://www.itorian.com/2013/02/jquery-ajax-get-and-post-calls-to.html
EDITED: 2016-07-20
Example:
$(function () {
$("searchField").keyup(function () {
$.ajax({
type: "POST",
url: "/Controller/Action",
data: data,
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
});
You have to visit the server to get data from server and without ajax it is not possible. Now the question is how to make ajax call, you can use jQuery js lib to do but I would recommend you to try angular as data binding in angular will fulfill your needs.
Take a look at followings links
Angular Ajax Service -
jQuery Ajax

New value in HTML.DropDownListFor(...) not setting in Controller [Post] method?

Hopefully someone can see how to go about this, because I've tried everything I can think of. When the Create() View in my MVC5 application loads I first populate several [SelectList(...)]'s in my Controller (ex.):
ViewBag.Model_Id = new SelectList(db.DBT_MODELS.OrderBy(x => x.MODEL_DESCRIPTION), "MODEL_ID", "MODEL_DESCRIPTION");
I then on my Create() View use this [SelectList(...)] to Populate an Html.DropDownListFor(...):
<div class="form-group">
<span class="control-label col-md-2">Model:</span>
<div class="col-md-4">
#Html.DropDownListFor(model => model.MODEL_ID, (SelectList)ViewBag.Model_Id, htmlAttributes: new { #class = "form-control dropdown", #id = "selectModel" })
#Html.ValidationMessageFor(model => model.MODEL_ID, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
<div class="btn-group">
<button id="createNewModel" type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
</div>
</div>
<div class="col-md-4">
<div id="createModelFormContainer" style="display:none">
<form action="/createNewModel">
<input type="text" id="textNewModel" name="model_description" placeholder="New Model" />
<input type="button" id="submitNewModel" value="Submit" />
<input type="button" id="cancelNewModel" value="Cancel" />
</form>
</div>
</div>
</div>
Simple enough, and this all works as expected. The problem lies in a bit of extended functionality I've tried to incorporate. My main class has several of these properties which are basically Foreign Key's in my DB. When a User goes in to Create/Edit() an entity in my main Model, I wanted to allow them to be able to add new entities to these foreign tables without needing to navigate away from the current View.
As such, I added (for each foreign property, using (Model) as an example) the code shown above and again directly below with a button to Show/Hide a small form for users to insert a new value and have it added to the DropDownList:
<div class="col-md-2">
<div class="btn-group">
<button id="createNewModel" type="button" class="btn btn-success" aria-expanded="false">CREATE NEW</button>
</div>
</div>
<div class="col-md-4">
<div id="createModelFormContainer" style="display:none">
<form action="/createNewModel">
<input type="text" id="textNewModel" name="model_description" placeholder="New Model" />
<input type="button" id="submitNewModel" value="Submit" />
<input type="button" id="cancelNewModel" value="Cancel" />
</form>
</div>
</div>
My submitNewModel() click event below gets the user's inputted new value and then uses a JSON call to a Controller Method to add it in the Database Table. This new value (and new ID for it) are then returned, the form for the DropDownList is reset, and I set the DropDownList's current value as the newly added one:
$('#createNewModel').click(function () {
$('#createModelFormContainer').show();
})
$('#cancelNewModel').click(function () {
$('#createModelFormContainer').hide();
})
$('#submitNewModel').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewModel').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewModel", "INV_ASSETS")',
data: data,
success: function (resp) {
if (resp.ModelExists)
{
alert("Model [" + resp.Text + "] already exists. Please select from the DropDown.");
} else {
$('#selectModel').append($('<option></option>').val(resp.MODEL_ID).text(resp.Text));
form[0].reset();
$('#createModelFormContainer').hide();
var count = $('#selectModel option').size();
$('#selectModel').prop('selectedIndex', count - 1);
$('#selectModel').val(resp.MODEL_ID);
//document.getElementById('selectModel').value = resp.MODEL_ID; - Shows dropdown as blank [ ] once executed.
}
},
error: function () {
alert("ERROR - Something went wrong adding new Model [" + resp.Text + "]!");
$('#createModelFormContainer').hide();
}
});
//reloadForNewEntity();
});
The createNewModel() method that is called in my Controller:
public JsonResult createNewModel(string description)
{
DBT_MODELS model = new DBT_MODELS()
{
// ID auto-set during save.
MODEL_DESCRIPTION = description.Trim(),
CREATED_DATE = DateTime.Now,
CREATED_BY = System.Environment.UserName
};
var duplicateModel = db.DBT_MODELS.FirstOrDefault(x => x.MODEL_DESCRIPTION.ToUpper() == model.MODEL_DESCRIPTION.ToUpper());
try
{
if (duplicateModel == null)
{
if (ModelState.IsValid)
{
db.DBT_MODELS.Add(model);
db.SaveChanges();
// Ensure the [model.ID] is properly set after having been saved to and auto-generated in the database.
model.MODEL_ID = db.DBT_MODELS.FirstOrDefault(x => x.MODEL_DESCRIPTION.ToUpper() == model.MODEL_DESCRIPTION.ToUpper()).MODEL_ID;
}
}
else
{
model = duplicateModel;
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = model.MODEL_ID, Text = model.MODEL_DESCRIPTION, ModelExists = (duplicateModel != null) }, JsonRequestBehavior.AllowGet);
}
Visually speaking, everything works as intended up to this point. The problem is when I go to Save the main entity I am Creating/Editing.
Any value that was already in the Foreign Tables, and thus in the DropDownList when the View loads, saves just fine; but if I add a new Foreign Table value for these main entity properties (though visually added and the currently selected values for the individual DropDownLists) the [POST] method then executes with each foreign id value set as 0 (ex. MainClass.Model_ID = "0" vs expected MainClass.Model_ID = "625", MainClass.Type_ID = "0" vs expected MainClass.Type_ID = "17", MainClass.Location_ID = "0" vs expected MainClass.Location_ID = "82", etc.)
Basically if the value selected in the Html.DropDownListFor() is one of my newly added values, the POST controller method always renders the MainClass.*_ID value which the selected Html.DropDownListFor() value corresponds to as "0".
Can anyone point me to how to get this working? I have tried:
Changing how my JavaScript sets the value in the DropDownList after the the JSON call to my Controller Actions returns (ex): //document.getElementById('selectModel').value = resp.MODEL_ID; - Shows dropdown as blank [ ] once executed. vs $('#selectModel').val(resp.MODEL_ID); which visually renders the expected new value in the DropDownList.
On return from the Controller method, setting a new ViewBag variable and then hoping to reference the saved value in the POST method (did not work, the JavaScript rendered my #Viewbag.PostModelID = resp.ModelID as "= resp.ModelID" and threw many expected errors).
EDIT:
[Redacted for N/A]
EDIT2: Good to go. Thanks everyone for the suggestions!
The json data you are returning from your action method is in this format.
{
"ID": 24,
"Text": "IOS",
"ModelExists": false
}
But in your code, you are trying to access MODEL_ID property which does not exist in the resp object.
$('#selectModel').append($('<option></option>').val(resp.MODEL_ID).text(resp.Text));
Change your code to use ID property value
$('#selectModel').append($('<option></option>').val(resp.ID).text(resp.Text));
$('#selectModel').val(resp.ID);
In your controller where you create the new model.. your json object that you're returning is ID, Text, ModelExists, but in your javascript you're setting the val property of the new <option> to MODEL_ID.. these 2 need to match..
So change your javascript to be
.val(resp.ID)
or change the return value in your controller action to
return Json(new { MODEL_ID = model.MODEL_ID, Text = model.MODEL_DESCRIPTION
You're also referencing MODEL_ID here
$('#selectModel').val(resp.MODEL_ID);
so make sure if you don't change your controller action, you update this also

pass model from view to controller with html.actionlink

I am trying to get the model data from a strongly typed view to a controller.
Using the submit button is ok, I can get the data. Now I want to achieve the same with html.actionlink.
This is what I have:
View:
#model WordAutomation.Models.Document
#{
ViewBag.Title = "Document";
}
<script type="text/javascript">
$(function () {
$("#dialog").dialog();
});
</script>
<h2>Document</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Document</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ClientTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientTitle)
#Html.ValidationMessageFor(model => model.ClientTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientFullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientFullName)
#Html.ValidationMessageFor(model => model.ClientFullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientCustomSSN)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientCustomSSN)
#Html.ValidationMessageFor(model => model.ClientCustomSSN)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null, new { id = "previewLink" })
</div>
<div id="dialogcontainer">
<div id="dialogcontent"><input type="submit" value="Create" /> </div>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function() {
$("#dialogcontainer").dialog({
width: 400,
autoOpen:false,
resizable: false,
title: 'Test dialog',
open: function (event, ui) {
$("#dialogcontent").load("#Url.Action("PreviewWordDocument", "Home")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$("#previewLink").click(function(e) {
e.preventDefault();
$("#dialogcontainer").dialog('open');
});
});
</script>
}
Controller:
public ActionResult Document()
{
return View();
}
[HttpPost]
public ActionResult Document(WordAutomation.Models.Document model)
{
Models.Utility.EditWord word = new Models.Utility.EditWord();
word.EditWordDoc(model);
return View("Display", model);
}
public ActionResult PreviewWordDocument()
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
The document actionresult can get the model, but I want to know how can I get the values from the actionlink which will trigger the PreviewWordDocument action.
Thanks in advance, Laziale
The form can only be posted using the submit button to the URL given by its action attribute.
You can however send the form data to a different URL using the jQuery post method, manually validating the form before it is sent.
That way you can send the form data to the PreviewWordDocument controller method and handle the response in order to show the preview in the desired div.
(It will be helpful if you give an id to the form, so you can easily find it using jQuery)
So your click event handler for the preview link will look like this:
$("#previewLink").click(function(e) {
e.preventDefault();
if($("#YourFormId").valid()){
$("#dialogcontainer").dialog('open');
}
});
In the open function of the dialog you will post the form (which was already validated) to the preview controller method, using the jQuery ajax function. The response will be loaded into the dialogContent div:
$.ajax({
type: "POST",
url: $("#previewLink").attr("href"), //the preview controller method
data: $("#YourFormId").serialize(),
success: function (data) {
//load ajax response into the dialogContent div
$("#dialogcontent").html(data);
},
error: function(xhr, error) {
$("#YourFormId").prepend('<div id="ajaxErrors"></div>')
.html(xhr.responseText);
}
});
Now you will now be able to receive the whole document in the PreviewWordDocument action:
public ActionResult PreviewWordDocument(WordAutomation.Models.Document model)
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
in a HTML page when you click on a submit button all the input elements inside the form which the submit button resides in will posted to server, but when you click on a anchor (<a> tag ). you only send a request with a Get method and without posting any value.but if you want to send particular value to the server with this approach you can do it by query string.you have used following to make a request :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null,
new { id = "previewLink" })
this will produce :
<a id="previewLink" href="/Home/PreviewWordDocument"> Preview </a>
which is incorrect.to pass any value to the server with ActionLink use 4th parameter like this :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home",
new { id = "previewLink" }, null)
the result from this code would be :
Preview
cheers!

Resources